Collection Frameworks Cheatsheet
- All Collection Classes implement Serializable and Cloneable
- Heterogeneous Objects - allowed for all collections except TreeSet and TreeMap.
Interface and Class Hierarchy
I = Interface AC = Abstract Class Underlying Data Structure mentioned beside the classes.
💡 Every Collection class is based on some standard data structure.
In order of hierarchy:
- Collection Interface (I)
- List (I)
- ArrayList - Resizable Array
- LinkedList - Doubly Linked List
- Vector - Resizable Array
- Stack - Stack
- Set (I)
- HashSet - Hash table
- Linked HashSet - Hash table
- SortedSet (I)
- NavigableSet (I)
- TreeSet - Balanced Tree
- NavigableSet (I)
- HashSet - Hash table
- Queue (I)
- Map (I)
Important Differences
Collections Class vs Collection Interface
From ArrayList
Go to text →
Comparison with Arrays
data.structure.primary.array (Private) | ArrayList | |
---|---|---|
Definition | An array is a dynamically-created object. It serves as a container that holds the constant number of values of the same type. It has a contiguous memory location. | The ArrayList is a class of Java Collections framework. |
Size | Static - fixed-length data structure | Dynamic - variable length data structure - can resize itself when needed |
Size specification | Mandatory to provide size while initializing | Size can be left unspecified - default initial capacity will be used |
Performance | Fixed size => Faster | Internally backed by array. Resize operation slows down the performance |
Primitive/generic type | Can store both primitives and objects | Can't store primitives - automatically converts them to objects. For example, int is converted to Integer. |
Getting the length | arr.length | arr.size() |
Adding elements | Can add elements using assignment operator | add() function |
Multiple dimensions | Can be multi-dimensional | CAN'T be multi-dimensional |
HashMap vs Hashtable
HashMap | Hashtable | |
---|---|---|
Introduced in | 1.2 | 1.0 |
Thread Safety | Not thread safe (not synchronized) => works with single thread | Thread safe (synchronized) => works with multiple threads |
Speed | Faster | Slower |
Null key | One null key allowed | Null key not allowed |
ArrayList and Vector's only Difference
Vector is thread-safe (most methods are synchronised) ArrayList is not.
💡 If something is thread-safe, it will inevitably have a lower performance in comparison to a corresponding non-synchronised something.
size()
vs capacity()
- size = number of objects currently
- capacity = number of objects which can be accommodated