ArrayList Declaration
What is difference when we declare ....
List lst = new ArrayList ();
and ....
ArrayList lst = new ArrayList();
what exactly we achive...?
What is difference when we declare ....
List lst = new ArrayList ();
and ....
ArrayList lst = new ArrayList();
what exactly we achive...?
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
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.
> 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
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.
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.