Reputation: 5522
I'm developing for Android and wondered, what are the main differences between an ArrayList
and a List
?
Upvotes: 5
Views: 9338
Reputation: 4162
List
is an interface and ArrayList
is an implementation of the List
interface. The ArrayList
class has only a few methods in addition to the methods available in the List
interface.
Have a look at the short article on JavaBeat - Difference Between List and ArrayList?
Upvotes: 0
Reputation: 6614
user370305 gives an exact explanation. This may also help you understand the collections hierarchy in Java.
Upvotes: 8
Reputation: 109237
For the handling of objects collection in Java, Collection interface have been provided. This is available in java.util package
.
"List" is an interface, which extends collection interface, provides some sort of extra methods than collection interface to work with collections. Where as "ArrayList" is the actual implementation of "List" interface.
The ArrayList class has only a few methods in addition to the methods available in the List interface. There is not much difference in this. The only difference is, you are creating a reference of the parent interface in the first one and a reference of the class which implements the List (i.e) the ArrayList class in the second. If u use the first, you will be able to call the methods available in the List interface and you cannot make calls to the new methods available in the ArrayList class.Where as, if you use the second one, you are free to use all the methods available in the ArrayList.
EDIT:
In Java Applications development, when you are supposed to pass the collection framework objects as arguments to the methods, then it is better to go with
List tempList = new ArrayList();
somemethodcall(tempList);
because, in future due to performance constraints, if you are changing the implementation to use linkedlist or some other classes which implements List interface, instead of ArrayList, you can change at only one point (i.e) only the instantiation part. Else you will be supposed to change at all the areas, where ever, you have used the specific class implementation as method arguments.
Upvotes: 8
Reputation: 365
There is a good article on wikipedia about that, where the arraylist is called "dynamic array".
If you are trying to optimize your application you should take a look at the table next to the article.
Upvotes: 1
Reputation: 7905
List
is interface which ArrayList
implements. If you are trying to create a method which needs a List
of some kind but you are not bothered what implemntation is actually used then use List
.
If you are actually instantiating a class then you have to pick some implementation of List
one of which is ArrayList
List<String> l1 = new ArrayList<String>();
would be an example.
You can not instantiate an interface and so would get an error if you tried to do the following:
List<String> l2 = new List<String>();
Upvotes: 3