0

Here is a two way of declaring a arraylist

1. List<String> l1 = new ArrayList<String>();
2. ArrayList<String> l2 = new ArrayList<String>();

My question is whats the difference between these two declaration.

And which is best way to declare an arraylist?

Roman C
  • 49,761
  • 33
  • 66
  • 176
786543214
  • 855
  • 4
  • 14
  • 29

2 Answers2

1

The main difference is that in the first you are saying that the type of l1 is the interface List<T>, whereas in the second case, the type of l2 is the concrete implementation (of List<T>) ArrayList<T>.

I would use the first form:

List<String> l1 = new ArrayList<String>();

Type using interfaces so that you can switch implementations easily later. The second implementation is tightly coupled to the ArrayList implementation of List. So if you wanted to change implementations later (say to LinkedList<T> for example), you would have a lot of refactoring to do (changing method signatures, etc.). However if you used the first approach, you can simply swap out the implementation without having to do any additional refactoring.

Using the interface also forces you to code against the contract of the interface than any particular concrete-implementation.

Vivin Paliath
  • 94,126
  • 40
  • 223
  • 295
  • Conversationally: have you ever wanted to do that in the case of a List? I use the interface because it is less typing, not because it is more plug & play really ;) – Gimby Dec 04 '13 at 17:16
  • Haha, well I can't think of a situation off the top of my head where I had to do this, but there are certain performance guarantees you get while using a one implementation vs. the others. So if while profiling you are able to narrow the performance problem as due to using a non-optimal (in that particular context) implementation of `List`, you can try using another implementation and then profiling again. In this case, swapping out the implementation is much easier because you used the interface as the type. – Vivin Paliath Dec 04 '13 at 17:18
0

Use the first approach, since it would allow you to reassign the List reference to a different subclass later.

BTW, I've never seen anybody using the second approach.

Sorter
  • 9,704
  • 6
  • 64
  • 74