我一直在阅读 Effective Java 并且遇到了 unbounded Collection 类型<?>。但是,阅读使我相信您不能将除 之外null的任何元素放入Collection<?>.
所以,我的问题是:实例化 a 的目的是什么,Collection<?>因为我们只能插入null元素,因为它似乎毫无意义。我一直试图弄清楚这个概念,但它似乎没有多大意义。任何帮助将非常感激。
我一直在阅读 Effective Java 并且遇到了 unbounded Collection 类型<?>。但是,阅读使我相信您不能将除 之外null的任何元素放入Collection<?>.
所以,我的问题是:实例化 a 的目的是什么,Collection<?>因为我们只能插入null元素,因为它似乎毫无意义。我一直试图弄清楚这个概念,但它似乎没有多大意义。任何帮助将非常感激。
Collection<?> allows you to create, among other things, methods that accept any type of Collection as an argument. For instance, if you want a method that returns true if any element in a Collection equals some value, you could do something like this:
public boolean collectionContains(Collection<?> collection, Object toCompareTo) {
for (Object o : collection) {
if (toCompareTo.equals(o)) return true;
}
return false;
}
This method can be called by any type of Collection:
Set<String> strings = loadStrings();
collectionContains(strings, "pizza");
Collection<Integer> ints = Arrays.toList(1, 2, 3, 4, 5);
collectionContains(ints, 1337);
List<Collection<?>> collections = new ArrayList<>();
collectionContains(collections, ILLEGAL_COLLECTION);
考虑文档中的以下 Util 方法
以下方法向您展示了如何使用迭代器来过滤任意集合 - 即遍历集合删除特定元素。
static void filter(Collection<?> c) {
for (Iterator<?> it = c.iterator(); it.hasNext(); )
if (!cond(it.next()))
it.remove();
}
这段简单的代码是多态的,这意味着它适用于任何Collection实现方式。
当您使用通配符声明集合时,您指定该集合是所有类型的集合的超类型。
当您有一个方法要传递所有类型的集合时,这非常有用,例如:
void printCollection(Collection<?> c) {
for (Object e : c) {
System.out.println(e);
}
}
查看Oracle关于通配符的文档,因为它非常详尽。
Collection是所有Lists和的最低抽象Sets。最好用作您可以使用的最低抽象,因为它在未来为您提供了更大的灵活性并且您的代码更健壮,因为它可以处理所有Lists或Sets其他实现,甚至还不需要实现。
好吧, Collection 在某种程度上等同于Collection<Object>. 这只是意味着存储在其中的对象的通用类型Collection是未知的,或者您可以使用任何对象Object本身的最低抽象。在这种情况下,您可以放入Collection任何对象,甚至可以将其与不同类型混合。但是您必须注意在运行时将其转换为正确的类型,因为您没有提供您的 Collection 存储的 Object 类型。因此,Collection 无法将 Object 转换为适合您的类型,您必须自己完成。要识别正确的类型,您应该使用Object instanceof SomeOtherClass或Class.isAssignableFrom(Class)在运行时。
也Collection没有实现get()方法,但您可以通过Iterator这种方式从集合中获取和获取对象。