In most of the Java code that uses collections,i see something like this.
List<String> list = new ArrayList<String>();
But i always wondered why it is preferred over
ArrayList<String> = new ArrayList<String>();
I researched a bit but wasnt able to understand a lot.
Because when using the object by its interface you can later change the implementation. For example:
But after a while it appears
ArrayListis inefficient for what it is mostly used by the callers of this method, so you decide to change it toLinkedList.Listyou are doneArrayListyou should go to all places that the method is invoked and change that. And what if someone used some arraylist-specific methods – you have to think how to refactor that. And that’s the good scenario. If your code is a library and other branches/companies are using it you may be stuck with the inefficient code.See also: