简体   繁体   English

使用泛型返回接口时应使用哪种数据类型?

[英]What datatype to use for return of Interface using generics?

With this interface: 使用此界面:

interface SomeInterface<E> {
  List<E> getList();
}

And this implementation: 而这个实现:

private void someMethod(SomeInterface someImplementation) {
  Object item = someImplementation.getList().get(0);  // here
}

What would be the appropriate datatype to use? 使用什么合适的数据类型? Just Object , as shown? 只是Object ,如图所示?

private <T> void someMethod(SomeInterface<T> someImplementation) {
  T item = someImplementation.getList().get(0);  // here
}

Object is fine too, as long as you don't need to do something like someImplementation.getList().add(item) later. Object也很好,只要以后不需要执行诸如someImplementation.getList().add(item) The key to this example is that it avoids the use of a raw type, so that the compiler can ensure that you've written type-safe code. 此示例的关键是避免使用原始类型,以便编译器可以确保您编写了类型安全的代码。

An alternative way to avoid the use of raw types is to use a wildcard ? 避免使用原始类型的另一种方法是使用通配符? in the signature. 在签名中。 If you did it that way the appropriate type for item would be Object : 如果这样做,则item的适当类型Object

private void someMethod(SomeInterface<?> someImplementation) {
    Object item = someImplementation.getList().get(0);  
}

The downside of doing it this way is that you cannot use the generic type E in the body of the method. 这样做的缺点是您不能在方法的主体中使用泛型E

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM