Reputation: 1015
Can someone please explain what the difference between 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?
Upvotes: 10
Views: 4519
Reputation: 129507
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;
}
This is all covered in the generics tutorial (see the wildcards section).
Finally, 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.
Upvotes: 19
Reputation: 155
ArrayList<?>
means "an ArrayList
instance containing a type which is to be determined"
ArrayList
is the class of an ArrayList
An ArrayList<Object>
means an instance of ArrayList
containing Object
types.
This looks like it could be a good write-up on this (and more): http://docs.oracle.com/javase/tutorial/java/generics/types.html
Upvotes: 1