You are on page 1of 12

Impl ADT Data Structure Performance (Big O

notation)

ArrayList List Array of objects. add(E element)


A new array is created method: O(1) amortized. That
(sync) and populated whenever is, adding n elements within
elements are added capacity: constant time O(1).
beyond the current Adding an element beyond
length (capacity) of the capacity: O(n) times.
underlying array. It's better to specify initial
capacity at construction if
known.

remove(int index): O(n -


index), removing last is O(1).
All other operations
including get(int index) run
in linear time O(1) .
The constant factor of O(1) is
low compared to that for the
LinkedList implementation.

LinkedList List, Doubly-linked list. Each get(int index), remove(int


Deque element has memory index): O(n)
(sync) addresses of the add(E element) and others:
previous and next item Constant time O(1).
used internally.

Vector List Array of objects. Similar Similar to ArrayList but slower


to ArrayList because of synchronization.
(sync)
(Legacy)

Stack List Array of Similar to Vector/ArrayList but


extends Vector objects. LIFO (Last in slower because of
(sync) first out). synchronisation.
(Legacy) It provides addition
methods empty(), peek(),
pop(), push(E e) and
search(Object o)

HashSet Set Backed by HashMap add, remove, contains, size:


(a Hash table data O(1)
(sync) structure). Elements of Iteration: O(n + capacity).
the set are populated as Better don't set initial capacity
(size of backing hasMap) too
key of the HashMap. high or load factor too low if
Allows at most one null. iteration is frequently used.

LinkedHashSet Set Backed by add, remove, contains, size:


LinkedHashMap where O(1)
(sync) elements of this Iteration: O(n), slightly slow
LinkedHashSet are that of HashSet, due to
populated as key of the maintaining the linked list.
Map. Maintains elements
in insertion order. Allows
at most one null.

TreeSet NavigableSet Backed by TreeMap add, remove, contains: O(log


(a red-black tree data n)
(sync) structure). The elements Iteration: O(n) slower than
of this set are populated HashSet.
as key of the Map.
Doesn't permit null.

EnumSet Set Bit vectors All methods: O(1). Very


All of the elements must efficient
(sync) come from a single
enum type.

PriorityQueue Queue Binary Heap offer, poll, remove() and


Unbounded add: O(log n)
(sync) Elements are ordered to remove(Object),
their natural ordering or contains(Object) O(n)
by a provided peek, element, and size:
Comparator. O(1)

ArrayDeque Dequeue Resizable-array (similar remove,


to ArrayList). removeFirstOccurrence,
(sync) Unbounded removeLastOccurrence,
Nulls not permitted. contains, iterator.remove(),
and the bulk operations:
O(n)
All other operations O(1)
amortized
Synchronization
It's not recommended to use legacy collections. One advantage of using
them might seem to be that they are synchronized. java.util.Collections
provides methods to wrap any collection around a new collection which is
synchronized. These methods are:
Collection<T> synchronizedCollection(Collection<T> c)
Set<T> synchronizedSet(Set<T> s)
SortedSet<T> synchronizedSortedSet(SortedSet<T> s)
NavigableSet<T> synchronizedNavigableSet(NavigableSet<T> s)
List<T> synchronizedList(List<T> list)

Read Only Collections


java.util.Collections provides methods to wrap any collection and return a
new Collection which are read only. Attempts to modify (calling mutative
methods), directly or via iterators will
cause UnsupportedOperationException. Followings are the methods:
Collection<T> unmodifiableCollection(Collection<T> c)
Set<T> unmodifiableSet(Set<T> s)
SortedSet<T> unmodifiableSortedSet(SortedSet<T> s)
NavigableSet<T> unmodifiableNavigableSet(NavigableSet<T> s)
List<T> unmodifiableList(List<T> list)
Impl ADT Data Structure Performance (Big O
notation)

EnumMap Map Fixed size Array of 'value' All methods O(1). Likely
objects initialized to full size of (though not guaranteed) to
(sync) underlying enum elements. be faster than their
Keys = A The indexes of the 'value' HashMap counterparts.
single enum array are the enum ordinals. Iterators returned by the
type Null keys are not permitted. collection views are weakly
elements, Maintained in the natural order consistent.
Values = any of their keys (per ordinals, the
object. order in which the enum
constants are declared)

HashMap Map Hash table: maintains an array get, put: O(1)


of buckets. Each bucket It can be O(n) if we use
(sync) contains one or more bad hashCode causing
key/value pairs. One particular more elements added to
key's hash (retrieved using one bucket.
hashCode() method of the key Iteration over collection
object) is masked to the views requires time
buckets array index. Since proportional to the capacity
multiple keys are allowed to of the map plus its size.
have same hash (hash Thus, it's very important
collisions), each bucket's not to set the initial
element maintains a linked capacity too high (or the
data structure (having load factor too low) if
references of other key/value iteration performance is
pairs). After matching hash important.
code, the particular match Java 8
within a bucket linked Optimization: Under high
structure is searched using hash-collision conditions
key's equal() method, that O(log n). Balanced trees
also means if two keys have are used internally rather
same hash per hashCode() than linked lists to store
method then they should not map entries.
be same per equal() method.
Permits at most one null key.
capacity : no of buckets
(default 16)
Load Factor : rehash factor
(default 0.75f i.e 75% of map
size). When (capacity * load
factor) >= (size of the map),
then bucket array size is
doubled (an expensive
process). e.g. default 16 *
0.75 = 12 means when storing
the 12th key/value pair into
the map , its capacity becomes
32.

Hashtable Map Hash table: Similar to Same as HashMap ignoring


HashMap but is thread-safe. synchronization overhead.
(sync) null is not permitted for keys No Java 8 tree nodes
(Legacy) or values. optimization.

LinkedHashM Map Hash table + Doubly-linked get, put: O(1) (Similar to


ap list. HashMap)
Insertion-order of the keys is It can be O(n) if we use
(sync) maintained. bad hashCode causing
Insertion order is not affected more elements added to
if a key is re-inserted. one bucket.
Permits at most one null key.
Performance is likely to be
just slightly below that of
HashMap, due to additional
maintenance of the linked
keys, with one
exception: Iteration over
the collection-views of a
LinkedHashMap requires
time proportional to the
size of the map, regardless
of its capacity. Iteration
over a HashMap is likely to
be more expensive,
requiring time proportional
to its capacity.

IdentityHash Map Hash table. get, put: O(1)


Map A special Map where all It can be O(n) if
methods use == for System.identityHashCode(
(sync) comparing keys instead of Object) doesn't disperse
equals() method. elements properly among
Should be used whenever each buckets or maximum limit
key has a single global is crossed.
instance (memory reference) Iteration over collection
e.g when using views requires time
java.lang.Class, strings proportional to the number
returned by String.intern() or of buckets in the hash
proxy objects. table, so it pays not to set
Permits at most one null key. the expected maximum
No need to override equal() size too high if we are
and hashCode() methods for especially concerned with
key object. iteration performance or
System.identityHashCode(Ob memory usage.
ject) is used for bucket It uses simple linear
allocations. probing, rather than
Expected Max Size is the only separate linked-list
tuning parameter (user cannot chaining, hence the
specify capacity or load performance is better than
factor). Internally, this HashMap.
parameter is used to
determine the number of
buckets. If size of the map
exceeds beyond maximum
size, the number of buckets
are increased (rehashing, an
expensive process).

WeakHashMa Map Hash table. This class has performance


p Weak keys: An entry in this characteristics similar to
map will automatically be those of the HashMap
(sync) removed when its key is no class.
longer in ordinary use. That is,
it will not be prevented from
being garbage collected.
Because the garbage collector
may discard keys at any time,
a WeakHashMap may behave
as though an unknown thread
is silently removing entries.
Permits at most one
null key.
Initial capacity and load
factor are the tuning
parameters (just like
HashMap)

TreeMap Navigable Red-black tree. containsKey, get, put,


Map Null keys are not permitted. remove: O(log n)
(sync) Iteration over collection
views: O(log n)
Synchronization
java.util.Collections provides methods to wrap any map around a new
map which is synchronized. These methods are:
Map<K,V> synchronizedMap(Map<K,V> m)
Map<K,V> synchronizedSortedMap(SortedMap<K,V> m)
Map<K,V> synchronizedNavigableMap(NavigableMap<K,V> m)

Note: It's not recommended to use legacy Hashtable.

Read Only Maps


The util class java.util.Collections also provides methods that return an
unmodifiable view of the specified map. These methods allow to provide
client code with "read-only" access to internal maps. Query operations on
the returned map "read through" to the specified map, and attempts to
modify the returned map, whether direct or via its collection views, result
in an UnsupportedOperationException. Those methods are:
Map<K,V> unmodifiableMap(Map<? extends K,? extends V> m)
SortedMap<K,V> unmodifiableSortedMap(SortedMap<? extends K,?
extends V> m)
NavigableMap<K,V> unmodifiableNavigableMap(NavigableMap<K,?
extends V> m)

You might also like