rgamber rgamber - 1 year ago 97
Java Question

ArrayList declaration


Possible Duplicate:

ArrayList declaration Java




In Java, why is an ArrayList often declared using a List?

List<String> strList1 = new ArrayList<String>();
ArrayList<String> strList2 = new ArrayList<String>();


I am not able to understand the difference between these two. Is one better than the other? or have a specific use?

Answer Source

The ArrayList class implements the List interface.

It is usually a good practice to declare an object of the type of the interface and of course instantiate it using an implementation of that interface.

This way, you can change the implementation when needed, but the declared type stays unchanged. This way, you could avoid modifying too much code especially in the methods getting the variable as a parameter. The method keeps getting a List as a parameter, not a certain implementation.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download