Summary
Vector and ArrayList
- Vector is synchronized, ArrayList is not synchronized
- ArrayList is faster
- Both grow and shrink dynamically, the increment of ArrayList is 50%, the increment of Vector is 100%
- Both have Enumeration and Iterator
- ArrayList is preferrable when there is no specific requirement
ArrayList and LinkedList
- ArrayList is an implementation of dynamica array, LinkedList is a double linked list
- Insertion is O(1) with LinkedList, O(n) in worst-case and O(1) in best-caset with ArrayList
- Removal is O(1) with LinkedList, O(n) with ArrayList
- LinkedList has more memory overhead
- Accessing an element is O(n) with LinkedList, O(1) with ArrayList
- Search is O(n) for both, but ArrayList is able to use binary search which is O(logn)
TreeMap, HashMap and LinkedHashMap
- HashMap
- It is implemented by an array of linked lists
- 0(1) lookup and insertion
- A HashMap contains values based on the key
- It contains only unique elements
- It may have one null key and multiple null values
- It maintains no order
- LinkedHashMap
- It is implemented by doubly-linked buckets
- 0(1) lookup and insertion
- A LinkedHashMap contains values based on the key
- It contains only unique elements
- It may have one null key and multiple null values
- It is same as HashMap instead maintains insertion order
- TreeMap
- TreeMap is implemented by a Red-Black Tree
- O(log N) lookup and insertion
- A TreeMap contains values based on the key
- It contains only unique elements
- It cannot have null key but can have multiple null values
- It is same as HashMap instead maintains ascending order sorted using the natural order of its key
- Hashtable
- A Hashtable is an array of list
- It contains only unique elements
- It may have not have any null key or value
- It is synchronized
HashMap and Hashtable
- HashMap is non synchronized. It is not-thread safe and can’t be shared between many threads without proper synchronization code whereas Hashtable is synchronized. It is thread-safe and can be shared with many threads
- HashMap allows one null key and multiple null values whereas Hashtable doesn’t allow any null key or value
- HashMap is generally preferred over HashTable if thread synchronization is not needed
- HashMap is an advanced version and improvement on the Hashtable. HashMap was created later
Hash and WeakHashmap
- In HashMap , entry object(entry object stores key-value pairs) is not eligible for garbage collection
- In WeakHashmap, when a key is discarded then its entry is automatically removed from the map
Remove Elements
- It is not recommended to use remove() of list interface when iterating over elements. This may lead to ConcurrentModificationException (Refer this for a sample program with this exception). When iterating over elements, it is recommended to use Iterator.remove() method
Reference