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();
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.
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.
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.
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.
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
.
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