top of page

Subscribe to Wisdom

Thanks for Subscribing!

Writer's picturePuru Uttam

ArrayList vs LinkedList in Java

Both are the implementations of List interface and both of them are non-synchronized classes.

They are needed to solve the problem with the size of an array which is predefined and fixed.

They support storage of all types of objects due to the use of generics in them.


There are few differences between them which need to be considered while using ArrayList and LinkedList.


ArrayList :

  • It internally uses a dynamic array to store its elements.

  • There is slow manipulation because it internally uses an array. If any element is removed from the array, all the other elements present are traversed or shifted in memory.

  • It is efficient to use when the application demands storing the data and accessing it widely as it provides constant time for search operation.

  • It implements List Interface only so has all the properties of a list.

  • It creates an array with some initial capacity. So, if we need to store more items than the default capacity, it will replace that array with a new and bigger array.


//In this case, the initial capacity of the ArrayList will be 50, //bydefault it's 10.
ArrayList<String> arrayList = new ArrayList<>(50); 

  • ensureCapacity() method can be used to increase it's size in between.


//Increasing capacity from 50 to 500
ArrayList<String> arrayList = new ArrayList<>(50);
arrayList.add("A");
arrayList.add("B");
arrayList.add("C"); 
arrayList.ensureCapacity(500);

LinkedList :

  • It internally uses a doubly linked list to store its elements.

  • There is faster manipulation than ArrayList because of doubly linked list , which means If any element is removed from it, only references will be changed.

  • It is efficient to use when the application demands manipulation of the data as it provides constant time for add and remove operations.

  • It implements List Interface as well as Deque Interface , so has all the properties of a list and queue.

  • It doesn't have default capacity concept as an empty list can also be created during initialization .

  • When you don't need random access to any elements, prefer LinkedList.



import java.util.LinkedList;
import java.util.List;

public class ListExamples {
public static void main(String... args) {      
List<String> linkedList = new LinkedList<>();
      linkedList.add("A");
      linkedList.add("B");
      linkedList.add("C");
System.out.println(linkedList);
}
}



13 views0 comments

Recent Posts

See All

Comments


Modern Digital Watch
bottom of page