Tuesday, February 12, 2013

SCJP: Collection and Map summary

Collections comes with 4 flavors:

Set - Unique things
List - List of things, non-unique, cares about the index
Queue - Things arranged by the order to be processed
Map - Things with a unique ID (key, value pairs)

Map
HashMap - Unsorted, unordered. Allows one null key and multiple null values.
Hashtable - that's right, with lower case in table word, because of Java prehistoric times. Synchronized version of a HashMap, but with the difference of not allowing anything that is null.
TreeMap - Sorted, by using natural order (Comparable) or with a specific order (using a Comparator).
LinkedHashMap - Maintains insertion order.
If the element to be added already exists, then it is replaced. Returns the previous value or null if it did not exist.

Set
HashSet - Unsorted, unordered. Uses hashcode of the element being inserted to determine the insertion bucket and the uses equals to determinate unicity. If the hashcode of the object is not redefined, the it uses the default Object hashcode (always returns a different value for each object that seems to be meaningfully equal). Does not allow duplicates
LinkedHashSet - Ordered version of HashSet, using insertion order. Does not allow duplicates
TreeSet - Sorted, by using natural order (Comparable) or with a specific order (using a Comparator). Does not allow duplicates
If the element to be added already exists, then the insertion does nothing and returns false.

List
ArrayList - ordered collection (by index) but not sorted. Duplicates allowed.
Vector - Synchronized version of an ArrayList. Duplicates allowed
LinkedList - ordered collection, by index, and provides you extra methods for inserting/removing from head/tail. Duplicates allowed

Queue
PriorityQueue - Sorted, by using natural order (Comparable) or with a specific order (using a Comparator). The elements ordering represents their priority.

Utility classes
Collections
Arrays

One way of thinking about collections is the following:

Sorted Collections (objects need to implement Comparable):
TreeMap - natural order (compare from Comparable) or custom comparison rules (compareTo from Comparator)
TreeSet - natural order (compare from Comparable) or custom comparison rules (compareTo from Comparator)
PriorityQueue - natural order (compare from Comparable)

Ordered Collections:
LinkedHashMap - by insertion order
LinkedHashSet - by insertion order
ArrayList -by index
Vector - by index
LinkedList - by index

Unordered Collections (by hashcode):
HashMap
Hashtable
HashSet
(2)

(2)


(1)

(1)

(1) From book A Programmer's Guide to Java SCJP Certification: A Comprehensive Primer (3rd Edition)
(2) From book SCJP Sun Certified Programmer for Java 6 Exam 310-065

No comments:

Post a Comment