Vikash Ananda wrote:In general we must use List arrList=new ArrayList(); and likewise for other similar things because the implementation of class ArrayList can be changed by Sun in newer version of Java hence operations on ArrayList may fail on newer version of JDK but using List arrList=new ArrayList(); the code is safe from upgradation of JDK.
For safety purpose the good idea one is better approach if JDK is upgraded.
Sorry Vikash, but your answer is wrong. This is not the reason why you'd want to use List vs. ArrayList on the left side of the =. The implementation of ArrayList is not going to change in a newer version of Java so that "operations on ArrayList may fail". And using List instead of ArrayList is not going to make your code "safe" in any way with regard to a new version of Java.
Fred gave the correct answer: It's because you don't want to lock yourself in to one specific implementation of interface List (in this case, ArrayList).
Suppose that later you find out that it would be better to use another implementation of List, for example LinkedList. If you would have made the variable arrList an ArrayList, this means you would have to search through the whole program, and check everywhere where arrList is used if it's not doing something specific for ArrayList. If you would have written this:
then you would only have to change that line of code to the following:
The rest of the program only knows that arrList is a List, so you're sure that the program doesn't use any ArrayList-specific stuff on arrList.