Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are most of the examples using ArrayList

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?

like image 875
Shervin Asgari Avatar asked Oct 20 '10 14:10

Shervin Asgari


People also ask

Why do we use ArrayList?

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.

What are the benefits of using ArrayList objects?

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.

Why is ArrayList generally the best performing implementation?

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.

Where is ArrayList used in real life?

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.


2 Answers

I'd recommend to read Performance Myths, which explains which are the advantages and problems of defining a variable as List or ArrayList.

like image 71
Knife Avatar answered Oct 01 '22 22:10

Knife


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

like image 21
Michael Borgwardt Avatar answered Oct 01 '22 22:10

Michael Borgwardt