-3

I use this two statements to ArrayList definition:

ArrayList<String> my = new ArrayList<>();
List<String> my2 = new ArrayList<>();

Which one should i use?

Sajad
  • 2,273
  • 11
  • 49
  • 92

3 Answers3

3

With your second definition, you could later replace ArrayList constructor for another type of List, like a LinkedList or a high-performant list, or any other kind of list that may exist in the future. In your first definition, you are tied to the ArrayList implementation forever. You cannot change it, because the rest of your code is trusting in this reference being explicitly an ArrayList.

By using an interface, on the contrary, your code relies on a contract, that of the interface, and not in a particular implementation (like ArrayList). That gives you the power of changing implementations without affecting its users. And change is something that we must foster and plan ahead, simply because we cannot prevent things from changing.

Edwin Dalorzo
  • 76,803
  • 25
  • 144
  • 205
1

The latter. Program to an interface, not to an implementation.

djechlin
  • 59,258
  • 35
  • 162
  • 290
1

Depends on what you need. It's generally advised to use interfaces (hence List) if possible, otherwise you're sticked to implementation class. Say, you use ArrayList as input parameter of some method. For some reason (e.g. performance) you decide at some point to switch from ArrayList to LinkedList. So you must change also the type of the input parameter. If you use interface (List), you're more free to switch implementation without the need of refactoring code.

Cromax
  • 1,822
  • 1
  • 23
  • 35