In this guide, we will discuss, when to use ArrayList and when to use LinkedList in Java. There are multiple similarities between these classes. However there is a significant difference between ArrayList and LinkedList, when we talk about the performance of various operations such as add, update, delete, search etc.
When to use ArrayList and when to use LinkedList in Java
1) LinkedList add method gives O(1) performance while ArrayList gives O(n) in worst case. This is because every time you add an element, Java ensures that it can fit the element so it grows the ArrayList. Similar case with the remove operation.
The insert and remove operations give good performance (O(1)) in LinkedList compared to ArrayList(O(n)). Hence if there are frequent addition and deletion in application then LinkedList is a best choice.
2) 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.
Search (get method) operations are fast in Arraylist (O(1)) but not in LinkedList (O(n)) so, if there are less add and remove operations and more search operations requirement, ArrayList would be your best bet.
ArrayList Example in Java
import java.util.*; public class JavaExample { public static void main(String[] args) { ArrayList<String> list=new ArrayList<String>(); list.add("Chaitanya"); list.add("BeginnersBook"); list.add("Website"); list.add("Tutorials"); System.out.println("ArrayList elements: "); for(String str:list){ System.out.println(str); } } }
Output:
ArrayList elements: Chaitanya BeginnersBook Website Tutorials
LinkedList Example in Java
import java.util.*; public class JavaExample { public static void main(String[] args) { LinkedList<String> fruits = new LinkedList<String>(); fruits.add("Apple"); fruits.add("Mango"); fruits.add("Banana"); fruits.add("Orange"); //print LinkedList System.out.println("LinkedList elements: "); for(String str:fruits){ System.out.println(str); } } }
Output:
LinkedList elements: Apple Mango Banana Orange
Recommended Articles: