Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List versus ArrayList as reference type?

Tags:

Ok so I know that Set, List and Map are interfaces but what makes the first line of code any better than the second line?

List myArr = new ArrayList(); ArrayList myArr = new ArrayList(); 
like image 842
Julio Avatar asked Oct 31 '10 11:10

Julio


People also ask

Is it better to use List or ArrayList?

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.

Why do we use List instead of ArrayList Java?

It's preferable to do this because it makes your code more resilient to changes in the implementation. If for some reason it was decided that a different List implementation should be used, code that was programmed to the List interface would not need to be changed extensively.

Is ArrayList a reference type?

Base 4: Since ArrayList can't be created for primitive data types, members of ArrayList are always references to objects at different memory locations (See this for details). Therefore in ArrayList, the actual objects are never stored at contiguous locations.

Is List reference in Java?

Yes, a List that you pass to a method is passed by reference. Any objects you add to the List inside the method will still be in the List after the method returns.


1 Answers

If you use the first form, you are saying all you are ever going to use is the functionality of the List interface - nothing else, especially nothing extra added by any implementation of it. This means you can easily change the implementation used (e.g. just substitute LinkedList for ArrayList in the instantiation), and not worry about it breaking the rest of the code because you might have used something specific to ArrayList.

like image 188
MAK Avatar answered Oct 10 '22 04:10

MAK