1/03/2012

Java Collection and Map


Interface: Collection, List, Set, Map.
Class: ArrayList, LinkedList, Vector, HashSet, TreeSet, HashTable, HashMap, TreeMap.
           (Stack is inherited from Vector)
Difference between List and Set:
List can have duplicated elements but Set cannot.


Difference between ArrayList, LinkedList and Vector:
ArrayList and LinkedList are not synchronized.
Vector is synchronized.


ArrayList and Vector are based on Array, but with dynamic size. 
LinkedList is based on linked list, there is a pointer in each node, pointing to the next element.


Looking up element:
ArrayList and Vector support random access, but LinkedList does not, it needs to read from the head.


Inserting and deleting element:
ArrayList needs to move elements that is behind the target index.
LinkedList needs to move pointer.
So, if the target index is in the end of the list, ArrayList is fast. Otherwise, LinkedList is fast.


So, when you need to add/remove lots number of elements randomly in the List, and read from head in sequence, LinkedList is better.
When you need to add/remove lots number of elements at end of the list and randomly read data, ArrayList is better.


Difference between HashSet and TreeSet:
HashSet: Elements are not sorted.
TreeSet: Elements are sorted. Sorting algorithm: Red Black Tree. 
               Either the elements in the set has implemented comparable interface, or define Comparator when defining the TreeSet Object.


Difference between HashTable, HashMap and TreeMap:
TreeMap: Asynchronized.
                If needs to be synchronized, can use synchronizedSortedMap method:
               1 SortedMap m = Collections.synchronizedSortedMap(new TreeMap(...));
                Elements are sorted.
Difference between HashTable, HashMap is discussed in the previous article.



No comments:

Post a Comment