Developing Java, you have always learned that its best to create an ArrayList by using the List interface as the type for the variable the list is stored in. Like this
List<String> myList = new ArrayList<String>();
However, by looking at a lot of the android examples that is included in the bundle, they have created the list by using the Class.
ArrayList<String> myList = new ArrayList<String>();
Is there any reason why this is done? Is it faster, lighter or something to explicitly setting the Class?
ArrayList provides constant time for search operation, so it is better to use ArrayList if searching is more frequent operation than add and remove operation. The LinkedList provides constant time for add and remove operations. So it is better to use LinkedList for manipulation.
In short, ArrayList is more flexible than a plain native array because it's dynamic. It can grow itself when needed, which is not possible with the native array. ArrayList also allows you to remove elements which are not possible with native arrays.
Reason: ArrayList maintains index based system for its elements as it uses array data structure implicitly which makes it faster for searching an element in the list. On the other side LinkedList implements doubly linked list which requires the traversal through all the elements for searching an element.
An ArrayList can be used in Java Application when. 1. We want to add duplicate elements to the list. Since Java ArrayList class allows duplicate elements, we can add duplicate elements to the list.
I'd recommend to read Performance Myths, which explains which are the advantages and problems of defining a variable as List or ArrayList.
Personally, I believe that the thing "you have always learned" misses the point. This:
List<String> myList = new ArrayList<String>();
has very little maintenance benefit. If you want to change it to a different implementation, it's still only one line to change if you use the implementation type. However, a totally different matter is this:
public void process(List<String> list) {
Here, using the interface really matters because it allows people who call the method to use different implementations without having to change the method signature (which they may not be able to do).
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