Collections – List – ArrayList and LinkedList:
So far we have already discussed regarding Set and Map. In this article we are going to discuss regarding Lists. There are two types of Lists – ArrayList and LinkedList – (HashSet here and HashMap here)
Difference Between ArrayList and LinkedList:
ArrayList | LinkedList |
---|---|
ArrayList uses array to store the elements | LinkedList uses doubly linked list to store the elements |
ArrayList needs to know the size or it will re-create when it needs to grow | LinkedList grows dynamically |
ArrayList Manipulation is slow since it is an array | LinkedList Manipulation is fast |
When should we use ArrayList and When to use LinkedList:
ArrayList:
- When random access of elements are needed
- If we know the size of array ahead so we can allocate the memory
LinkedList:
- When we need more insertions/deletions
- When we do not know the size to be allocated
Example Program:
import java.util.List; import java.util.LinkedList; public class ListExample { public static void main(String args[]){ List linkedList = new LinkedList(); //Inserting into linkedlist for(int i=0; i<9; i++){ linkedList.add(i); } //Reading from LinkedList for(Object l1: linkedList){ System.out.print(l1+" "); } //finding an element in linkedlist for(int i=0; i<linkedList.size();i++){ if(linkedList.get(i).equals(3)){ System.out.println("Found"); } } //Removing from List linkedList.remove(4); //Reading from LinkedList after Removing for(Object l1: linkedList){ System.out.print(l1+" "); } } }