0% found this document useful (0 votes)
4 views10 pages

Java Collections Framework – Comprehensive Guide

The Java Collections Framework (JCF) provides a unified architecture for storing and manipulating groups of objects, defining core interfaces and concrete implementations such as List, Set, Map, and their respective classes. It includes utility classes and algorithms for various operations, with a focus on performance and use-cases for each collection type. The document also compares common implementations and provides best practices for selecting the appropriate collection based on specific needs.

Uploaded by

Dhruv Dixit
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views10 pages

Java Collections Framework – Comprehensive Guide

The Java Collections Framework (JCF) provides a unified architecture for storing and manipulating groups of objects, defining core interfaces and concrete implementations such as List, Set, Map, and their respective classes. It includes utility classes and algorithms for various operations, with a focus on performance and use-cases for each collection type. The document also compares common implementations and provides best practices for selecting the appropriate collection based on specific needs.

Uploaded by

Dhruv Dixit
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Java Collections Framework – Comprehensive

Guide
The Java Collections Framework (JCF), introduced in JDK 1.2, provides a unified architecture for storing
and manipulating groups of objects 1 . It defines core interfaces (such as Collection , List , Set ,
Queue , Deque , Map , etc.) and concrete implementations ( ArrayList , LinkedList , HashSet ,
TreeSet , HashMap , etc.) 2 3 . The framework also includes utility classes and algorithms for sorting,
searching, and more. Below we explore the hierarchy, code examples, comparisons, use-cases,
performance, and interview tips for the JCF.

Collections Framework Hierarchy


Figure: Core interfaces and classes in the Java Collections Framework (hierarchy of Collection , List , Set ,
Queue , Map , etc.) 4 . The root interface is java.util.Collection (for lists, sets, queues) 5 . Its
subinterfaces include List (ordered sequence), Set (unique elements), and Queue / Deque (for FIFO
or double-ended queues). Separately, java.util.Map is a top-level interface (not a subinterface of
Collection ) for key-value mappings 6 5 . Specialized interfaces like SortedSet / NavigableSet
and SortedMap / NavigableMap add sorted-order behaviors. Implementations include:

• List implementations: ArrayList (resizable array, unsynchronized) 7 , LinkedList (doubly-


linked list, also implements Deque ) 8 , Vector (synchronized array) 9 , Stack (LIFO stack,
subclass of Vector ).
• Queue/Deque implementations: PriorityQueue (heap-based priority queue) 10 ,
ArrayDeque (resizable-array deque), and LinkedList (implements Queue / Deque FIFO
operations) 8 10 .
• Set implementations: HashSet (hash table, unordered) 11 , LinkedHashSet (insertion-ordered
hash table) 11 , and TreeSet (red-black tree, sorted NavigableSet ) 11 .
• Map implementations: HashMap (hash table, unsynchronized, allows one null key) 12 ,
LinkedHashMap (insertion-ordered hash table) 13 , TreeMap (red-black tree, sorted
NavigableMap ) 14 , and Hashtable (legacy synchronized hash table) 9 .
• Other: The Properties class extends Hashtable for string key-value pairs (often for
configuration) 15 .

These relationships are illustrated in the diagram above 4 . In practice, a List maintains element order
and allows duplicates, while a Set prohibits duplicates (with TreeSet keeping elements in sort order)
16 17 . A Map stores key→value pairs; for sorted key maps TreeMap is used, while HashMap is the
general-purpose unordered map 3 .

1
Core Interfaces and Implementations

The Collection Interface

Collection<E> is the root of the framework (except Map ). It defines common methods like add ,
remove , size , iterator , etc. All concrete collections (e.g. lists, sets, queues) implement it 5 .

List and Its Implementations

The List<E> interface represents an ordered sequence. Key implementations:

• ArrayList<E> – A resizable-array list (unsynchronized). Oracle docs call it “the best all-around
implementation of List” 7 . It supports fast random access (O(1) get) and amortized O(1) adds at the
end, but O(n) for insertions/deletions in the middle (due to shifting) 18 .
• LinkedList<E> – A doubly-linked list implementing both List and Deque . It provides O(1) inserts/
removes at the ends, but O(n) for indexed access 18 . As Oracle notes, it “provides better
performance than ArrayList if elements are frequently inserted or deleted” 8 . It can also function
as a FIFO queue (using offer/poll ) or a stack (using push/pop ).
• Vector<E> – A legacy synchronized array list. It has similar behavior to ArrayList but with all
methods synchronized (thread-safe) 9 . Its iteration is fail-fast like other collections (modifications
during iteration throw ConcurrentModificationException ).
• Stack<E> – A subclass of Vector representing a LIFO stack (push, pop, peek). It is considered
legacy; for stack behavior, Deque (e.g. ArrayDeque ) is usually preferred now.

List<Integer> arrayList = new ArrayList<>();


arrayList.add(1);
arrayList.add(2);
arrayList.add(1, 10); // insert at index 1
System.out.println("ArrayList: " + arrayList); // [1, 10, 2]

LinkedList<String> linkedList = new LinkedList<>();


linkedList.add("a");
linkedList.addFirst("b");
linkedList.addLast("c");
System.out.println("LinkedList: " + linkedList); // [b, a, c]

Vector<Double> vector = new Vector<>();


vector.add(1.1);
vector.add(2.2);
double v = vector.get(1); // 2.2
System.out.println("Vector (thread-safe): " + vector);

Stack<String> stack = new Stack<>();


stack.push("apple");
stack.push("banana");

2
System.out.println("Stack pop: " + stack.pop()); // banana
System.out.println("Stack peek: " + stack.peek()); // apple

• Performance: As the Big-O table below shows, ArrayList has O(1) get, O(1) add(at end,
amortized), but O(n) for insert/remove at arbitrary positions 18 . LinkedList has O(n) for
get(index) and contains() , but O(1) for adding/removing at head or tail 18 .

Queue, PriorityQueue, and Deque

The Queue<E> interface models a FIFO queue. Common implementations:

• PriorityQueue<E> – A heap-based unbounded priority queue (elements ordered by natural order or


a provided Comparator ) 10 . Inserts and removals ( offer / poll ) take O(log n) time. The head
of the queue is the least element.
• ArrayDeque<E> – A resizable-array double-ended queue ( Deque ), supporting element insertion
and removal at both ends in O(1) time. It is not thread-safe but is generally faster than
LinkedList for queue operations.
• LinkedList<E> – Also implements Queue and Deque with FIFO behavior. Its offer / poll at
ends are O(1) 8 .

Queue<Integer> pq = new PriorityQueue<>();


pq.offer(30);
pq.offer(10);
pq.offer(20);
System.out.println("PriorityQueue poll: " + pq.poll()); // 10 (smallest)

Deque<String> deque = new ArrayDeque<>();


deque.add("A");
deque.addFirst("B");
deque.addLast("C");
System.out.println("Deque first: " + deque.peekFirst()); // B
System.out.println("Deque last: " + deque.peekLast()); // C

• Performance: PriorityQueue has O(log n) insertion/removal, O(1) peek. ArrayDeque and


LinkedList queues have O(1) offer/poll/peek 19 .

Set and Its Implementations

The Set<E> interface enforces unique elements. Key implementations:

• HashSet<E> – Hash table implementation of Set . Unordered, allows one null element. Operations
add , remove , contains are O(1) on average 20 . It is the typical all-purpose set.
• LinkedHashSet<E> – Like HashSet , but maintains a doubly-linked list of entries to preserve
insertion order. Performance is similar to HashSet (all basic ops O(1) amortized) 21 . Use it when
predictable iteration order is needed.

3
• TreeSet<E> – Sorted set based on a red-black tree ( NavigableSet ). Elements are ordered by their
natural ordering or a supplied Comparator . Operations add , remove , contains are O(log n)
21 . Does not allow null elements (for natural order).

Set<String> hashSet = new HashSet<>();


hashSet.add("apple");
hashSet.add("banana");
hashSet.add("apple"); // duplicate ignored
System.out.println("HashSet: " + hashSet);

Set<String> linkedHashSet = new LinkedHashSet<>();


linkedHashSet.add("A");
linkedHashSet.add("C");
linkedHashSet.add("B");
System.out.println("LinkedHashSet (insertion order): " + linkedHashSet);

Set<Integer> treeSet = new TreeSet<>();


treeSet.add(5);
treeSet.add(1);
treeSet.add(3);
System.out.println("TreeSet (sorted): " + treeSet); // [1, 3, 5]

• When to use: HashSet for fastest lookup when order doesn’t matter. LinkedHashSet if you
need to iterate in insertion order. TreeSet when you need a sorted set (for example, maintaining a
sorted list of items) 22 21 . As GFG notes: use HashSet for unique objects (no order),
LinkedHashSet to preserve insertion order, and TreeSet when sorting is needed 22 .

Map and Its Implementations

The Map<K,V> interface stores key→value mappings. Important implementations:

• HashMap<K,V> – Hash table, unsynchronized, allows one null key and multiple null values. It’s
generally the “best all-around” map 12 . Average get/put are O(1) 23 (worst-case O(n) in rare
collision scenarios).
• LinkedHashMap<K,V> – Extends HashMap with a linked list of entries. Maintains insertion order
(or access order if configured) 13 . Performance is slightly slower than HashMap due to ordering
overhead, but still O(1) for basic ops. Often used for LRU caches by overriding
removeEldestEntry .
• TreeMap<K,V> – Red-black tree implementation of NavigableMap . Keys are sorted by their natural
order or a Comparator . Guarantees O(log n) for get , put , etc. 14 . Does not allow null keys
(unless a custom comparator handles them).
• Hashtable<K,V> – Legacy synchronized hash table (no null keys or values) 9 . Generally replaced by
ConcurrentHashMap or a synchronized HashMap .

Map<String,Integer> hashMap = new HashMap<>();


hashMap.put("one", 1);

4
hashMap.put("two", 2);
System.out.println("HashMap get one: " + hashMap.get("one"));

Map<String,Integer> linkedHashMap = new LinkedHashMap<>();


linkedHashMap.put("x", 24);
linkedHashMap.put("y", 25);
System.out.println("LinkedHashMap keys: " + linkedHashMap.keySet());

Map<String,Integer> treeMap = new TreeMap<>();


treeMap.put("c", 3);
treeMap.put("a", 1);
treeMap.put("b", 2);
System.out.println("TreeMap (sorted keys): " + treeMap.keySet()); // [a, b, c]

Hashtable<String,String> hashtable = new Hashtable<>();


hashtable.put("k", "v");
System.out.println("Hashtable value k: " + hashtable.get("k"));

• Properties: A special subclass of Hashtable for string-based key/value pairs (often configuration).
As the Oracle docs state, Properties is a persistent set of properties, with both key and value as
String 15 . You typically use setProperty / getProperty and can load/store from streams.

Comparable and Comparator

To define custom ordering of objects (for sorted collections or sorting routines):

• A class can implement Comparable<T> and override compareTo(T o) to define its natural
ordering. For example, many Java classes ( String , Integer , etc.) implement Comparable ,
which allows methods like Collections.sort(list) to sort them automatically 24 . Oracle
notes: “Comparable implementations provide a natural ordering for a class”, enabling automatic sorting
24 . If you call Collections.sort(list) on a list of objects not implementing Comparable ,

you’ll get a ClassCastException .

• Alternatively, a Comparator<T> can encapsulate an ordering. It’s a functional interface with a


compare(T o1, T o2) method. You can sort collections with a custom comparator, e.g.
Collections.sort(list, comparator) or list.sort(comparator) . This is useful when
you need an ordering different from natural order, or when the class does not implement
Comparable .

class Person implements Comparable<Person> {


String name;
int age;
Person(String n, int a) { name = n; age = a; }
public int compareTo(Person p) {
return Integer.compare(this.age, p.age); // sort by age
}

5
public String toString() { return name+":"+age; }
}

List<Person> people = Arrays.asList(new Person("Alice",30), new Person("Bob",


25));
Collections.sort(people); // uses Person.compareTo (by age)
System.out.println(people); // [Bob:25, Alice:30]

// Using Comparator for custom order (by name)


Collections.sort(people, Comparator.comparing(p -> p.name));

Comparisons of Common Implementations

ArrayList vs LinkedList

• Underlying structure: ArrayList uses a resizable array; LinkedList uses a doubly-linked list.
• Access: ArrayList has O(1) random access (via index) 18 , whereas LinkedList must traverse
nodes (O(n)).
• Insertion/Removal: Inserting or removing in the middle of an ArrayList is O(n) (elements must
be shifted) 18 . In a LinkedList , adding/removing at the ends is O(1) (just pointer updates), but
finding the insertion point is O(n). If insertions/deletions are frequent and not always at the end,
LinkedList can be faster overall 8 .
• Memory overhead: ArrayList stores a contiguous array (waste only an occasional extra array
capacity). LinkedList stores each element in a node with two additional references (previous/
next), so it has more per-element overhead.
• Use case: Typically, ArrayList is preferred for most use-cases (better cache locality and random
access). LinkedList is chosen if you need constant-time insert/delete at the ends or iterating in
both directions.

HashMap vs TreeMap vs LinkedHashMap

Feature HashMap TreeMap LinkedHashMap

Unordered (no Keys sorted by


Insertion order (or access order if
Ordering guaranteed order) natural/comparator
configured) 13
12 order

Allows one null Does not allow


Null Keys/ Allows one null key, like
key and null null keys (throws
Values HashMap
values 12 NPE)

Performance O(1) average 23 O(log n) guaranteed O(1) average (slightly slower than
(get/put) (worst-case O(n)) 23 HashMap) 23

When a predictable iteration


General-purpose Sorted-map when
Use case order (insertion or LRU cache) is
map key order matters
needed 13

6
Note: LinkedHashMap can be used to implement LRU caches by overriding
removeEldestEntry .

HashSet vs TreeSet vs LinkedHashSet

Feature HashSet TreeSet LinkedHashSet

Sorted (by natural/


Ordering Unordered (no order) Insertion order 25
comparator)

Backed by a
Underlying Backed by a HashMap Backed by a LinkedHashMap
TreeMap

O(1) add/contains/ O(log n) add/contains/ O(1) add/contains/remove (like


Performance
remove 20 remove 21 HashSet)

Fast unique collection, Need a sorted set of Unique elements with


Use case
no ordering needed unique elements predictable (insertion) order 25

Use Cases and Best Practices


• Choosing by need: Use the collection that best fits your use-case. For example, if you need fast
random access to elements, use ArrayList ; if you mainly add/remove at ends, LinkedList or
ArrayDeque might be better. Use a Set when duplicates are disallowed; use a Map when
associating keys to values. If iteration order matters, choose LinkedHashSet or LinkedHashMap
(for insertion order), or TreeSet / TreeMap for sorted order.
• Coding to interfaces: Declare variables using the interface type (e.g.
List<String> list = new ArrayList<>(); ) rather than concrete classes 26 . This allows
easily swapping implementations without changing code.
• Generics: Always use generics to enforce type safety (e.g. List<Integer> ). This prevents runtime
ClassCastException and makes code clearer.
• Avoid customizing hashCode / equals : When using custom objects as Map keys or in Set ,
ensure they have correct and consistent equals / hashCode implementations. Prefer using
immutable types (like String , Integer , or immutable custom classes) as keys 26 .
• Use utility methods: The java.util.Collections class provides wrapper methods for common
tasks. For example, you can create immutable or synchronized collections via
Collections.unmodifiableList(someList) or
Collections.synchronizedMap(someMap) 27 . Use Collections.emptyList() ,
Collections.singleton() , etc. to get standard collection instances. Also use
Collections.sort(list) or Collections.shuffle(list) as needed.
• Thread safety: The legacy classes Vector and Hashtable are synchronized (thread-safe) but
generally slower. Prefer Collections.synchronizedList(new ArrayList<>()) or concurrent
collections ( CopyOnWriteArrayList , ConcurrentHashMap , etc.) for thread safety 9 . Almost
all collections (except concurrent ones) are fail-fast: modifying a collection while iterating it (except
via the iterator’s own remove ) will throw ConcurrentModificationException .
• Iteration performance: For large collections, remember that iterating with an index (like a for
loop on a LinkedList ) is slow (O(n²) total). Use an Iterator or enhanced-for loop instead.

7
• Avoid nulls if possible: Although some collections allow null , using null as a map key or inserting
null into a set can complicate logic.

Real-world example: To remove duplicates from a List while preserving order, one idiom is:

List<String> list = Arrays.asList("a","b","a","c");


List<String> unique = new ArrayList<>(new LinkedHashSet<>(list));
System.out.println(unique); // [a, b, c]

The above converts the List to a LinkedHashSet (which drops duplicates but keeps insertion order)
and back to a List .

Performance Complexity (Big-O)


The table below summarizes typical time complexities for key operations on common collection classes (N =
number of elements):

HashMap/ HashSet/
Type Operation ArrayList LinkedList TreeMap TreeSet Priorit
LinkedHashMap LinkedHashSet

Access get(index) O(1) 18 O(n) 18 – – – – –

O(log n) O(log
Search contains(o) O(n) 18 O(n) 18 O(1) avg 23 O(1) avg 20 O(n)
23 n) 21

O(1)
O(1) (at O(log n) O(log
Insert add / put amortized O(1) avg 23 O(1) avg 20 O(log
ends) 18 23 n) 21
18

remove(index/ O(1) O(log n) O(log


Remove O(n) 18 O(1) avg 23 O(1) avg 20 O(log
key) (ends) 18 23 n) 21

Key points: ArrayList provides constant-time positional access, but linear-time insert/remove except at the
end 18 . LinkedList has faster adds/removes at the ends, but slow random access 18 . HashMap/HashSet
have average O(1) for basic ops 20 23 (worst-case O(n) in case of many collisions). TreeMap/TreeSet
guarantee O(log n) for gets/puts 23 21 . PriorityQueue enqueues/dequeues in O(log n). The actual
constants and cache effects can also matter; for example, ArrayList iterations are very fast due to
contiguous memory.

Interview Tips and Example Notes


• Know interface vs implementation: Be clear that Collection is the root interface, with
subinterfaces List , Set , Queue etc. Remember that Map is separate and not a Collection .
• List vs Set vs Map: A List is ordered (elements indexed) and allows duplicates; a Set contains
only unique elements (and typically is unordered) 17 . A Map holds key→value pairs.

8
• Thread-safety: Vector and Hashtable are synchronized (legacy); most modern code uses
unsynchronized collections or the java.util.concurrent package. Discuss when to use
Collections.synchronizedX() or ConcurrentHashMap .
• Iterator vs Enumeration: Iterator replaces legacy Enumeration . Only Iterator has
remove() and is used by all collections (fail-fast).
• Removing items during iteration: Use Iterator.remove() , or use Java 8 streams or
removeIf to avoid ConcurrentModificationException .
• Comparable/Comparator: Understand how to implement ordering. You may be asked to sort a list
of custom objects – recall that the class should implement Comparable , or you must supply a
Comparator .
• Collisions and HashCodes: For maps/sets, understand that poorly implemented hashCode() can
degrade performance.
• Use-cases: Be prepared to suggest which collection fits a scenario. For example, “If you need a FIFO
buffer, use LinkedList or ArrayDeque ; for LIFO, use Deque ; for priority-based processing, use
PriorityQueue ; for lookup by key, use HashMap or TreeMap depending on ordering needs,”
etc.
• Utilities: Mention knowledge of Collections utility class (sorting, reversing, empty collections,
singleton collections) and the fact that Arrays.asList() provides a fixed-size list view.
• Example concept – LRU cache: A common example is using LinkedHashMap with
removeEldestEntry to implement an LRU cache.
• Performance discussion: Be ready to articulate the Big-O for add/get/remove for common
collections. The JCF interview guide suggests candidates must “understand and articulate” these
complexities 26 .

In summary, the Java Collections Framework offers a rich set of data structures. Choosing the right one
involves understanding ordering, nullability, synchronization, and performance characteristics. By
combining the concepts above – the hierarchy, usage patterns, complexity, and interview considerations –
one can effectively use and explain Java’s collections in both code and discussion.

Sources: Authoritative documentation and tutorials on Java collections 2 3 18 16 15 26 (plus the


embedded diagram image【6†】).

1 17 26 Java Collections Interview Questions and Answers | GeeksforGeeks


https://www.geeksforgeeks.org/java-collections-interview-questions/

2 3 7 8 9 10 11 12 13 14 27 Outline of the Collections Framework


https://docs.oracle.com/javase/8/docs/technotes/guides/collections/reference.html

4 Collections in Java | GeeksforGeeks


https://www.geeksforgeeks.org/collections-in-java-2/

5 6 Collections in Java - Everything You MUST Know | DigitalOcean


https://www.digitalocean.com/community/tutorials/collections-in-java-tutorial

15 Properties (Java SE 24 & JDK 24)


https://docs.oracle.com/en/java/javase/24/docs/api/java.base/java/util/Properties.html

9
16 21 22 25 Difference and similarities between HashSet, LinkedHashSet and TreeSet in Java |

GeeksforGeeks
https://www.geeksforgeeks.org/difference-and-similarities-between-hashset-linkedhashset-and-treeset-in-java/

18 19 20 23 Big-O summary for Java Collections Framework implementations? - Stack Overflow


https://stackoverflow.com/questions/559839/big-o-summary-for-java-collections-framework-implementations

24 Object Ordering (The Java™ Tutorials > Collections > Interfaces)


https://docs.oracle.com/javase/tutorial/collections/interfaces/order.html

10

You might also like