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?
The List is an interface, and the ArrayList is a class of Java Collection framework. The List creates a static array, and the ArrayList creates a dynamic array for storing the objects. So the List can not be expanded once it is created but using the ArrayList, we can expand the array when needed.
means you can assign any type of List to it and List<Object> means you can store any type of object into it. That's the real difference between List<?> and List<Object> in Java.
An array is a fixed-length data structure. ArrayList is a variable-length data structure. It can be resized itself when needed. It is mandatory to provide the size of an array while initializing it directly or indirectly.
ArrayList doesn't have length() method, the size() method of ArrayList provides the number of objects available in the collection. Array has length property which provides the length or capacity of the Array. It is the total space allocated during the initialization of the array.
The array is a specified-length data structure whereas ArrayList is a variable-length Collection class.
Generic List stores all data of the data type it is declared thus to getting the data back is hassle free and no type conversions required. 4. Generic List must be used instead of ArrayList unless specific requirement for projects higher than . Net 2.0 Framework.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With