1

When coding with Collections:

Why use:

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

Why not:

ArrayList<String> mList=new ArrayList<String>();

When I ask the answer is : "It is JAVA convention".

I need a comprehensive, logical and expressive answer on this.

akash
  • 22,664
  • 11
  • 59
  • 87
Puneet Sahota
  • 53
  • 1
  • 9
  • 1
    Eh, it is just a convention. Either one works, but it's a layer of abstraction, so that if you decide to change the type of list (`List mList = new LinkedList()`), you can do so without messing up any other references. – Pokechu22 Oct 23 '14 at 04:12
  • 2
    So you can change the List implementation if you decide to later without changing other code – Matt Coubrough Oct 23 '14 at 04:12
  • But in this case, The Array List must be having some more methods, additional to the List interface, Doesn't this way of programming eliminates me to use those additional features if any. – Puneet Sahota Oct 23 '14 at 04:15
  • @PuneetSahota Any additional features should be exposed through a subinterface, e.g. `List` extending `Collection`. – Paul Bellora Oct 23 '14 at 04:18
  • I am still confused as to why we need to use an Interface reference when we can use a class reference, i apologize for the inconvenivnce, i am new to JAVA so understanding some things takes time for me. – Puneet Sahota Oct 23 '14 at 04:20
  • You don't **need** to. If you do it the other way it works fine. It is literally just a convention; you can choose to do either but most people use `List` only. – Pokechu22 Oct 23 '14 at 04:24

0 Answers0