Collections in Java better programming practice
I see something similar in most java code that uses collections
List<String> list = new ArrayList<String>();
But I always wonder why it is more popular
ArrayList<String> = new ArrayList<String>();
I studied it, but I can't understand much
Solution
Because when using objects through its interface, you can change the implementation later For example:
public ArrayList<String> doSomething(..) { ... return arrayList; }
But after a while, it seems that ArrayList is most commonly used by callers of this method is inefficient, so you decide to change it to LinkedList
>If your method returns only list, you are done > if your method returns ArrayList, you should go to all places where the method is called and change it What if someone uses some ArrayList - specific method - you have to think about how to refactor it This is a good plan If your code is a library and other branches / companies are using it, you may encounter inefficient code
You can also see:
> What does it mean to “program to an interface”? > “Program to an interface”. What does it mean?