简体   繁体   中英

What is the difference between ArrayList<?>, ArrayList, ArrayList<Object>?

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?

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, eg 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM