In many places i have seen statement like this. List x=new ArrayList(); In Sun tutorial it is given like "In this way, the program does not become dependent on any added methods in a given implementation, leaving the programmer free to change implementations anytime that it is warranted by performance concerns or behavioral details" .
But i dont understand the significance of the above statement. why cant we use ArrayList x = new ArrayList? What is advantage of implementing a list?
The advantage is not having to change the type "ArrayList" everywhere you're using it later when you decide that -instead of ArrayList- you'd rather use a LinkedList, for example. You could simple write "List x = new LinkedList()" instead of "List x = new ArrayList()" and be done with it.
This is particularly important for method signatures. If a signature contains ArrayList for a parameter instead of List, then you may have to change a lot of code that uses the method (and it may not be possible at all for complex projects, or for libraries that get used by several client projects).
Most of the time it's enough to know that you have a simple List. So it's much better to declare the variable type as List if this satisfies your needs because later you can easily switch the implementation say from ArrayList to LinkedList and you on have to change it in one line of code and not all over the place. If you directly depend on an ArrayList on the other hand you may (accidentally) use methods which are only available in ArrayList but not in the List interface. This would make it much harder to change the implementation later (for whatever reasons).
then you may use a method specific to the LinkedList[example getLast(),getFirst()..etc]. in future if requirement change[or you want to implement ] to the ArrayList. how will you replace LinkedList dependent methods[ getLast()].
instead if you use like below
you cant use any method which is specific to the implementation class.