ArrayList<?>,ArrayList,ArrayList< Object> ;?有什么区别? [英] What is the difference between ArrayList<?>, ArrayList, ArrayList<Object>?
问题描述
有人可以解释一下 ArrayList <?>>
, ArrayList
和 ArrayList< Object>
是什么时候使用每个?它们全都是相同的还是每个在实现级别上都有不同的含义? Object
s,而 ArrayList <?>
是一个我们不确定的具体类型的列表(意思是除了 null
之外,我们不能添加任何内容)。当列表的类型不相关时,你可以使用后者。当您要执行的操作不取决于列表的类型时。例如:
public static boolean isBigEnough(ArrayList<?> list){
return list.size() > 42;
}
这些都覆盖在泛型教程(请参阅 最后, Can someone please explain what the difference between This is all covered in the generics tutorial (see the wildcards section). Finally, 这篇关于ArrayList<?>,ArrayList,ArrayList< Object> ;?有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
ArrayList
中没有类型参数的是原始类型:甚至允许它的唯一原因是为了向下兼容Java版本5以下,而且您应尽可能避免使用它。ArrayList<?>
, ArrayList
and ArrayList<Object>
is, and when to use each? Are they all same or does each have some different meaning at the implementation level?ArrayList<Object>
is specifically a list of Object
s whereas ArrayList<?>
is a list whose concrete type we are unsure of (meaning we can't add anything to the list except null
). You would use the latter when the list's type is irrelevant, e.g. when the operation you want to perform does not depend on the type of the list. For instance:public static boolean isBigEnough(ArrayList<?> list) {
return list.size() > 42;
}
ArrayList
with no type parameter is the raw type: the only reason it's even allowed is for backwards compatibility with Java versions under 5, and you should refrain from using it whenever possible.