在Bar
类中使用通配符类型泛型相比完全跳过它们有什么好处吗?
public class Foo<T> {}
public interface Bar {
public void addFoo(Foo<?> foo);
public Foo<?> getFoo(String name);
}
答案 0 :(得分:6)
有许多优点。
它们提供更多类型的安全性。例如,考虑Foo
是否为List
。如果您使用List
代替List<?>
,则可以执行此操作:
myBar.getFoo("numbers").add("some string");
即使列表只是假设包含Number
s。如果您返回List<?>
,那么您将无法向其添加任何(null
除外),因为列表类型未知。
Foo
。