0

Is there a diffence if I say :

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

and

ArrayList<String> names = new ArrayList<>();
Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
msmilkoff
  • 81
  • 7

2 Answers2

0

There is a difference. The first line is more general than the second line.

For example if you got a method which takes a List<String> as input parameter you can only pass a List<String> and not an ArrayList<String>.

If you don't need to use the ArrayList specific methods you should use the first line!

Parker_Halo
  • 505
  • 2
  • 19
0

Yes there is differences.

The (preferable) first case let you operate on your collection whatever is the concrete implementation of the concept of list. You can then further use another concrete type, while the following code stay valid.

In the second case, you may be tempted to use some specific methods of the concrete type and then changing the instanciation may impact more code, and make it much more difficult to evolve.

Jean-Baptiste Yunès
  • 34,548
  • 4
  • 48
  • 69