ArrayList Declaration

What is difference when we declare ....

List lst = new ArrayList ();

and ....

ArrayList lst = new ArrayList();

what exactly we achive...?

[182 byte] By [prady_joa] at [2007-11-27 10:47:13]
# 1

Exact difference is List != ArrayList

JL.Nayaka at 2007-7-28 20:23:39 > top of Java-index,Java Essentials,Java Programming...
# 2

This is asked here a lot.

Try http://www.google.com/search?hl=en&q=declare+list+as+arraylist+site%3Aforum.java.sun.com&btnG=Search

pbrockway2a at 2007-7-28 20:23:39 > top of Java-index,Java Essentials,Java Programming...
# 3

You're declaring the type to be List, rather than ArrayList, which means any implementation of List can be assigned to the variable rather than only an ArrayList. If that's confusing and you don't understand why that's a good idea I suggest searching as pbrockway2 suggested.

kablaira at 2007-7-28 20:23:39 > top of Java-index,Java Essentials,Java Programming...
# 4

> What is difference when we declare ....

>

> List lst = new ArrayList ();

>

> and ....

>

> ArrayList lst = new ArrayList();

>

> what exactly we achive...?

A much more flexible program.

If you use

ArrayList lst = new ArrayList()

you're tide to the ArrayList and cannot change it without changing the sorrounding code but if you use

List lst = new ArrayList()

and later on you decide to switch implementations to, e.g.,

List lst = new Vector()

all the surrounding code will continue to work because it was unaware of the old implementation type

manuel.leiriaa at 2007-7-28 20:23:39 > top of Java-index,Java Essentials,Java Programming...
# 5

As a matter of principal, the less you tell the compiler about the classes it's using the more flexible your program will be. If the compiler doesn't need to know what implementation of List is used, then you don't tell it.

malcolmmca at 2007-7-28 20:23:39 > top of Java-index,Java Essentials,Java Programming...
# 6

On the other hand, if you need some of the methods offered by ArrayList that are not in the List interface, such as clone() or removeRange(), declaring your variable a List will not work.

Other than that, I agree with the previous posters. I think I always declare my ArrayLists List (and my HashMaps Map etc. for the same reasons).

I know, I'm probably just repeating something someone has already said in a different thread.

OleVVa at 2007-7-28 20:23:39 > top of Java-index,Java Essentials,Java Programming...