我开始学习 Java,我有一个关于泛型的问题。
在这个方法中来自 Collection<E>
界面:
boolean containsAll( Collection <?> c);<br/>
boolean removeAll(Collection<?> c);<br/>
boolean retainAll ( Collection <?> c);
为什么参数是Collection <?> c
而不是 Collection <E> c
?
非常感谢
最佳答案
JDK 设计者希望像下面这样的代码成为可能:
Collection<String> strings = Arrays.asList("foo", "bar", "baz");
Collection<Object> objects = Arrays.asList("foo", 123);
strings.removeAll(objects);
// strigns now contains only "bar" and "baz"
(上面的代码可能无法完全编译,因为我不记得 Arrays.asList()
是如何捕获类型参数的,但它应该能说明问题。)
也就是说,因为您可以对任何一对对象调用 .equals()
并获得有意义的结果,所以您实际上不需要将这些方法限制为特定的项目类型。
关于Java 集合方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14804124/