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?
48
Upvotes
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.