Tuesday, March 24, 2015

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 class  extends from AbstractSequentialList class and   implements the List interface and Deque interface. When talk about  storing the data, LinkedList uses doubly linked lists to store data. As well as it maintains the insertion order. Further 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);
        }

    }

}


Now consider about 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);
        }

    }

}


Now move to discuss about  LinkedHashSet. As its name says this is a one of the  set implementation. It extends HashSet class. This uses List elements for storing data.Another main important point about linkedhashset is 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);
        }

    }

}


No comments:

Post a Comment