javaandroidoptimization

Should I use ArrayList<?> or List<?>


I'm developing for Android and wondered, what are the main differences between an ArrayList and a List?


Solution

  • 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.