r/learnjava • u/ThiccShadyy • Jul 27 '19
Is there a difference between declaring an Arraylist with List<> and with ArrayList<> ?
I learnt it as the latter and hadnt seen the first one until recently. I was trying a Leetcode question where the return type was given as List<Integer>. Returning an ArrayList which was declared using ArrayList<Integer> gave me a compilation error. So whats the exact difference between the two?
20
u/meempo8 Jul 27 '19
This gets into the fun topic of inheritance. I would start by reading about interfaces and how they are implemented. A quick TLDR: interfaces essentially define a contract that inherited classes must abide. For example, if you have a Car interface, it will define methods like start, stop, and go. Every car must do these things, therefore, any class that implements the Car interface must define these methods. If class Tesla implements the Car interface, then it must provide an implementation for start, stop, and go. The power of this interface is that now, whenever someone gives you an implementation of the Car interface, you know unequivocally that it implements start, stop, and go. However, in Tesla, you can also define your own methods, like autopilot.
In your situation, List works the same way. List defines a set of methods that ArrayList must implement (add, remove, size, etc). Therefore, it is completely legal to do the following: `List<Integer> list = new ArrayList<>` or `ArrayList<Integer> aList = new ArrayList<>`. The key difference here is that in 1, you are limited to only the methods defined in the list interface, but in 2, you get the benefit of also using the ArrayList methods. Therefore, 1 is more useful to limit scope (which is a huge plus when you know you're use case), while 2 is better if you need all of the methods from the ArrayList class available to you. The general practice in Java is to use interfaces as return types because it helps limit scope and debug more easily.
Hope this made sense!
4
u/iPissVelvet Jul 27 '19
Study up on the following topics:
Static vs dynamic type (Java)
Inheritance (Java)
And then look at the Javadocs for Arraylist.
26
u/stramash Jul 27 '19
List is an Interface that ArrayList implements.
This declaration:
List<Integer> list = new ArrayList<>
means that you are declaring to the compiler that list conforms to the List interface. You can return that from your method.
Meanwhile:
ArrayList<Integer> list = new ArrayList<>
means that list is an ArrayList. That class might share the same API as List, but that would be a happy coincidence and compilers don’t like that. Therefore, you can’t return something that is not explicitly a List from that method.