views:

77

answers:

4

Possible Duplicate:
Type List vs type ArrayList in Java

Why is it recommended to do this:

List<String> myArrayList = new ArrayList<String>

or same with Map interface and HashMap class

rather than:

ArrayList<String> myArrayList = new ArrayList<String>
+2  A: 

Possible duplicate here

npinti
Yup, its a dupe. closing.
zengr
+3  A: 

Because the consuming code of the myArrayList variable won't be tied to a particular implementation of this interface.

Darin Dimitrov
+1  A: 

With the first (preferred) line you say, that your code needs a List, with the second line you say your code needs an ArrayList. Usually, you path variable instances around. If you now change the myArrayList instance for some reason you would have to change too much code.

mklhmnn
A: 

You should not use:

List<String> myArrayList = new ArrayList<String>

Why you should use the type List instead of ArrayList (unless you really need feature of the ArrayList that is missing in the List interface) is already explained in the other answer.

But I think it is even more important to use proper names. So if you use List as type for the variable, the name should not tell that it is an ArrayList. It would be even better if the name indicated the use of the variable.

Yes, this is picky. But using good names will make it a lot easier to understand the code in a year from now and for colleagues.

nhnb