Possible Duplicate:
List versus ArrayList
Difference between
ArrayList al = new ArrayList()
and
List al = new ArrayList() ?
When you declare List l = new ArrayList() l is limited to the methods provided by the interface List, while when you declare it ArrayList al = new ArrayList() it can use all methods and fields in an arraylist.
ArrayList set() Vs. However, there is a major difference between them. The set() method adds a new element at the specified position by replacing the older element at that position. The add() method adds a new element at the specified position by shifting the older element towards the right position.
The List is an interface, and the ArrayList is a class of Java Collection framework. The List creates a static array, and the ArrayList creates a dynamic array for storing the objects. So the List can not be expanded once it is created but using the ArrayList, we can expand the array when needed.
None, from a creation perspective. Both create an instance of ArrayList
.
The difference is that, in you second example, al
allows access to all methods implemented on the List
interface while, in the first example, al
allows access to all (accessible) methods and fields of the ArrayList
class.
A practical rule of thumb: use the second pattern. If you need some extra goodies from the ArrayList
implementation, then you can always cast:
List list = new ArrayList();
// do some adds/removes/... on the list
((ArrayList) list).trimToSize();
Its called programming to interface. Suppose, you need to return this list
from your method. So the calling code can have that into a List
variable.
public ArrayList getList() {
ArrayList list = new ArrayList();
// do something with the list here
return list;
}
And this,
public List getList() {
List list = new ArrayList();
// do something with the list here
return list;
}
Now for the latter method calling code can have the returned list in List
type variable. And you can easily decide later, for some reason, something like this,
public List getList() {
List list = new LinkedList();
// do something with the list here
return list;
}
No change in calling code, whereas with the former you need to change the return type, that would eventually screw up the calling code as well.
Paraphrasing my answer to this very similar question about Map
vs. HashMap
:
There is no difference between the objects. There is a difference in the interface you have to the object. In the first case, the interface is ArrayList
, whereas in the second it's List
. The underlying object, though, is the same.
The advantage to using List
is that you can change the underlying object to be a different kind of list without breaking your contract with any code that's using it. If you declare it as ArrayList
, you have to change your contract if you want to change the underlying implementation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With