LinkedList VS ArrayList VS LInkedHashSet
Through this post I am going to discuss about the differences  among LinkedList , ArrayList and  LinkedHashSet and there behaviors.
LinkedList
- LinkedList class extends from AbstractSequentialList class and implements the List interface and Deque interface.
- LinkedList uses doubly linked lists to store data. 
- It maintains the insertion order. 
- LinkedLists can hold duplicate elements. Below code segment illustrates the behavior of LinkedList  class.
public class LinkedListEx {
    public static void main(String[] args) {
        
        LinkedList<String> list= new LinkedList<String>();
        list.add("hasitha");
        list.add("kamal");
        list.add("saman");
        list.add("amala");
        list.add("hasitha");
        
        for (String string : list) {
            System.out.println(string);
        }
    }
}
ArrayList
- It extends the AbstractList class and  implements the List Interface. 
- ArrayList has a initial size and after it exceeds the initial size, 
- Arraylist can dynamically increases its size.
- One main difference between arraylist and linkedlist is while arraylist uses arrays to store the data linkedlist uses nodes to store data.Most of the other behaviors are same in arraylists and linkedlist. Below code segment illustrates how arraylist works.
public class ArrayListEx {
    public static void main(String[] args) {
        
        ArrayList<String> cities= new ArrayList<String>();
        cities.add("matara");
        cities.add("colombo");
        cities.add("galle");
        cities.add("tangalle");
        cities.add("anuradhapura");
        
        for (String string : cities) {
            System.out.println(string);
        }
    }
}
LinkedHasSet
- As its name says this is a one of the set implementation.
- It extends HashSet class. This uses List elements for storing data. 
- It doesn't hold duplicate values since this is a set implementation. 
- And also this maintains the insertion order. Now consider about a coding example of LinkedHashSet.
public class LinkedHashSetEx {
    public static void main(String[] args) {
        
        LinkedHashSet<String> countries= new LinkedHashSet<String>();
        countries.add("Sri lanka");
        countries.add("India");
        countries.add("Korea");
        countries.add("Canada");
        countries.add("maldives");
        
        
        for (String string : countries) {
            System.out.println(string);
        }
    }
} 
Comments
Post a Comment