Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

generics

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?

like image 331
Karn_way Avatar asked Aug 29 '13 14:08

Karn_way


People also ask

What is difference between ArrayList and ArrayList <?> In Java?

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.

What is the difference between List <?> And List object?

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.

What's the difference between an array and ArrayList?

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.

What is the difference between an array's length and an ArrayList size?

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.

What is difference between array and List in Java?

The array is a specified-length data structure whereas ArrayList is a variable-length Collection class.

What is the difference between ArrayList and generic List?

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.


1 Answers

ArrayList<Object> is specifically a list of Objects 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.

like image 57
arshajii Avatar answered Oct 05 '22 23:10

arshajii