Aspect Iterable Iterator
An interface that An object that provides
represents a collection of methods to iterate through
Definition
elements that can be elements of a collection one
traversed. by one.
Defines the method Provides hasNext(), next(),
Methods iterator() which returns an and remove() for traversal
Iterator. and modification.
Used in enhanced for- Used explicitly when step-by-
Usage each loop to iterate over step traversal or removal of
a collection. elements is required.
Works at the collection Works at the element level,
Level of
level, declaring it can be giving sequential access to
Abstraction
iterated. elements.
An Iterator is obtained from
An Iterable produces an
Relationship an Iterable and cannot exist
Iterator for traversal.
independently.
List<String> list = new Iterator<String> it =
Example ArrayList<>(); → list is list.iterator(); → it is the
Iterable. Iterator.
Aspect Array ArrayList
A fixed-size data
A resizable class from the
structure used to store
Definition java.util package that
elements of the same
implements List interface.
type.
Size is fixed once Size is dynamic; it grows or
created and cannot shrinks automatically when
Size
grow or shrink elements are added or
dynamically. removed.
Can store both primitive Can only store objects.
Data Types types (e.g., int, char) Primitives must be wrapped
and objects. (e.g., int → Integer).
Provides faster access
Slightly slower than arrays
(direct index-based
Performance because it involves method
access using
calls and resizing overhead.
array[index]).
Less flexible;
operations like More flexible; provides
Flexibility insertion and deletion built-in methods like add(),
are difficult and remove(), contains(), etc.
manual.
ArrayList<Integer> list =
Usage int[] arr = new int[5];
new ArrayList<>(); →
Example → Array of integers.
Dynamic list of integers.
Aspect Enumeration Iterator ListIterator
Modern
Legacy interface for interface for Advanced iterator
iterating over iterating over that allows
Definition
collections, mainly collections in bidirectional
Vector and Hashtable. forward traversal of List.
direction.
Both forward and
Direction of Only forward
Only forward direction. backward
Traversal direction.
directions.
hasNext(), next(),
hasNext(),
hasMoreElements(), hasPrevious(),
Methods next(),
nextElement(). previous(), add(),
remove().
set(), remove().
Can add, remove,
Cannot modify Can remove
Element and modify
collection elements elements while
Modification elements during
while traversing. iterating.
traversal.
Works only with
Works with all
Works with legacy List
Applicable Collection
classes (Vector, Stack, implementations
Collections classes (List,
Hashtable). (ArrayList,
Set, Queue).
LinkedList).
Usage Enumeration e = Iterator it = ListIterator li =
Example v.elements(); list.iterator(); list.listIterator();
Aspect List Set
An ordered collection
An unordered collection that does
Definition that allows duplicate
not allow duplicate elements.
elements.
Maintains insertion Does not guarantee order
order (elements are (except LinkedHashSet maintains
Order
stored in the order insertion order, and TreeSet
they were added). maintains sorted order).
Allows duplicates;
Does not allow duplicates; if a
Duplicates multiple identical
duplicate is added, it is ignored.
elements can exist.
Provides index-based
Does not support index-based
Access by access (e.g., list.get(0)
access, elements are accessed
Index to access first
via iteration.
element).
Slightly slower for
Generally faster for search
search operations
Performance operations because of hashing
compared to Set
(HashSet) or sorting (TreeSet).
(especially large lists).
ArrayList, LinkedList, HashSet, LinkedHashSet,
Examples
Vector, Stack. TreeSet.
Aspect AbstractList ArrayList
A skeletal (abstract)
A concrete, resizable array-
implementation of the List
based implementation of the
Definition interface that provides a
List interface built on top of
framework for creating custom list
AbstractList.
implementations.
Abstract class (cannot be Concrete class (can be
Type
instantiated directly). instantiated directly).
Provides partial implementation
Provides a ready-to-use
of List so that subclasses only
Purpose dynamic array that can grow
need to implement core methods
or shrink automatically.
(get() and size()).
Meant to be extended by Already fully implemented; no
Implementation developers to create custom list need for additional
Responsibility implementations with specific implementation for standard
behavior. usage.
Offers flexibility for creating Limited to array-backed list
Flexibility tailored list types by overriding functionality; behavior is
methods. predefined.
class MyList extends AbstractList ArrayList<String> list = new
Example Usage
{ ... } ArrayList<>();
Aspect Vector ArrayList
A legacy class in java.util
A modern resizable array implementation
package that implements
Definition of the List interface, introduced in Java
a dynamic array,
1.2 (Collections Framework).
introduced in Java 1.0.
Not synchronized → faster but not
Synchronized → thread-
Thread- thread-safe (must use
safe but slower in single-
Safety Collections.synchronizedList() for thread
threaded applications.
safety).
Slower due to Faster as it does not have
Performance
synchronization overhead. synchronization overhead.
Doubles its size when Increases capacity by 50% when full
Growth
capacity is exceeded. (default behavior).
Considered a legacy
Legacy vs Part of the Collections Framework,
class, retained for
Modern widely preferred in modern applications.
backward compatibility.
Usage Vector<Integer> v = new ArrayList<Integer> list = new
Example Vector<>(); ArrayList<>();
Aspect ArrayList LinkedList
A resizable array
A doubly linked list implementation of
Definition implementation of the List
the List and Deque interfaces.
interface.
Underlying Uses a doubly linked list where
Uses a dynamic array to
Data each node holds data and references
store elements.
Structure to next and previous nodes.
Provides fast random
Access is slower (O(n)) because
Access (get / access (O(1)) since elements
traversal is needed from the head or
set) are stored in a contiguous
tail.
array.
Insertion and deletion are Insertion and deletion are faster
Insertion /
slow (O(n)) in the middle due (O(1)) if position is known (just
Deletion
to shifting of elements. relinking nodes).
Consumes less memory Consumes more memory because
Memory
since only data is stored in each node stores extra references
Usage
the array. (previous and next).
Suitable when frequent Suitable when frequent
Best Use
retrieval operations are insertions/deletions occur in the
Case
needed. middle of the list.
Aspect HashSet TreeSet
Implements the Set interface
Implements the Set interface using a
Definition using a hash table (backed
TreeMap (Red-Black Tree).
by HashMap).
Maintains elements in sorted
Does not guarantee order of
(ascending) order according to
Order elements (insertion order not
natural ordering or a custom
preserved).
Comparator.
Offers constant time O(1) for
Offers logarithmic time O(log n) for
Performance add, remove, and search
add, remove, and search operations.
operations on average.
Null Does not allow null elements (throws
Allows one null element.
Elements NullPointerException).
Preferred when sorted data is
Usage Preferred when fast lookups
needed while maintaining
Scenario and no ordering are required.
uniqueness.
HashSet<Integer> hs = new TreeSet<Integer> ts = new
Example
HashSet<>(); TreeSet<>();
Aspect HashSet LinkedHashSet
Implements the Set interface Subclass of HashSet that uses a
Definition using a hash table (backed by linked list + hash table
HashMap). combination.
Does not maintain any order of Maintains insertion order of
Order
elements. elements.
Provides constant-time O(1) Slightly slower than HashSet due
Performance performance for add, remove, to maintaining a linked list, but still
and search (on average). O(1) on average.
Null
Allows one null element. Also allows one null element.
Elements
Requires more memory because
Memory Requires less memory as only
it maintains a linked list in addition
Usage hashing is maintained.
to hashing.
Suitable when only uniqueness
Suitable when uniqueness with
Usage and fast performance are
predictable iteration order
Scenario needed without caring about
(insertion order) is required.
order.
Aspect LinkedHashMap Set
A Map implementation that stores
A Collection that stores only
key–value pairs and maintains
Definition unique elements and does not
insertion order (or access order if
allow duplicates.
specified).
Implemented using various data
structures like HashSet (hash
Data Based on hash table + doubly
table), LinkedHashSet (hash
Structure linked list (for order maintenance).
table + linked list), or TreeSet
(red-black tree).
Stores key–value pairs (e.g., key →
Stores only elements (no key–
Storage value). Keys must be unique, but
value mapping).
values can be duplicated.
Order depends on
Maintains insertion order (or access implementation: HashSet (no
Order
order with accessOrder=true). order), LinkedHashSet (insertion
order), TreeSet (sorted order).
Allows one null element (in
Null Allows one null key and multiple null
HashSet / LinkedHashSet), but
Handling values.
TreeSet does not allow null.
Used when you need to maintain a Used when you only need a
Usage
mapping of keys to values with unique collection of elements
Scenario
predictable iteration order. without key–value mapping.
LinkedHashMap<Integer, String> Set<Integer> set = new
Example
map = new LinkedHashMap<>(); HashSet<>();
Aspect Comparable Comparator
An interface used to define
An interface used to define custom
Definition the natural ordering of
ordering of objects.
objects.
Belongs to java.lang
Package Belongs to java.util package.
package.
Has a single method: Has a single method:
Method
compareTo(Object o). compare(Object o1, Object o2).
Number of Supports multiple sorting
Supports only one sorting
Sorting sequences (different comparators
sequence (natural ordering).
Sequences can be created).
Class must implement
No modification of the original class
Comparable, so modification
Modifications is required; separate comparator
of the class is required to
classes can be created.
define ordering.
Best when objects have a Best when different custom sort
Usage
default, natural order (e.g., orders are needed (e.g., sorting
Scenario
sorting numbers, strings). employees by name, then by salary).
class Student implements
Comparator<Student> byName =
Comparable<Student> {
Example (s1, s2) ->
public int compareTo(Student
s1.name.compareTo(s2.name);
s) { return this.id - s.id; } }
Aspect HashSet HashMap
Implements the Set interface and Implements the Map interface and
Definition
stores unique elements only. stores key–value pairs.
Internally uses a HashMap
Data Uses a hash table to store key–
(elements are stored as keys with
Structure value mappings.
a dummy value).
Does not allow duplicate Does not allow duplicate keys,
Duplicates
elements. but values can be duplicated.
Null Allows one null key and multiple
Allows one null element.
Handling null values.
Does not guarantee order of
Does not guarantee order
Order keys/values (unless using
(insertion order not preserved).
LinkedHashMap).
Suitable when only unique Suitable when you need to
Usage
elements are needed without associate keys with values (like
Scenario
mapping. a dictionary).
HashSet<String> set = new HashMap<Integer, String> map =
Example
HashSet<>(); new HashMap<>();
Aspect Iterator ListIterator
An interface used to traverse
A bidirectional iterator used to
Definition elements of any Collection (like
traverse elements of a List only.
Set, List, Queue).
Direction of Traverses in forward direction Traverses in both forward and
Traversal only. backward directions.
Can be used only with List
Applicable Can be used with all Collection
implementations (ArrayList,
Collections classes (Set, List, Queue).
LinkedList, etc.).
Methods hasNext(), next(), hasPrevious(),
hasNext(), next(), remove().
Provided previous(), add(), remove(), set().
Does not provide index of Provides index information using
Index Access
elements during traversal. nextIndex() and previousIndex().
Best for more complex traversals
Usage Best for simple, forward-only
where both directions and
Scenario iteration over a collection.
modifications are needed.
Iterator<String> it = ListIterator<String> li =
Example
list.iterator(); list.listIterator();
Aspect containsKey(Object key) containsValue(Object value)
Checks if the specified key is Checks if the specified value is
Definition
present in the map. present in the map.
Returns true if the map contains Returns true if the map contains the
Return Type
the given key, else false. given value, else false.
Looks up based on keys (fast, Looks up based on values (slower,
Search Basis
usually O(1) in HashMap). O(n) as it may scan all entries).
More efficient because map
Less efficient since it requires
Performance implementations are optimized
checking each entry's value.
for key lookups.
Works even if the key is null
Null Works if the value is null (multiple
(allowed only one null key in
Handling null values allowed in HashMap).
HashMap).
Used to verify the existence of a Used when you need to check if a
Usage
mapping key before accessing particular value is mapped to by
Scenario
or inserting. any key.
map.containsKey(101) → map.containsValue("Alice") →
Example
checks if key 101 exists. checks if "Alice" exists as a value.
Aspect put(K key, V value) putIfAbsent(K key, V value)
Inserts or updates the Inserts the mapping only if the key is
Definition mapping of a key to a not already associated with a value
value. (i.e., absent or mapped to null).
If the key already exists, If the key already exists with a non-null
Overwriting
the old value is replaced value, the existing value is retained (no
Behavior
with the new value. overwrite).
Returns the previous Returns the existing value if the key is
Return Value value associated with the present; otherwise, returns null after
key, or null if none. inserting.
Allows null key (in
Works similarly, but if key exists with
Null Handling HashMap) and multiple null
null value, it will insert the new value.
values.
Not inherently thread-safe Designed with concurrency in mind,
Thread-
(in HashMap), but available commonly used in ConcurrentHashMap
Safety
in concurrent maps too. to avoid race conditions.
Best when you want to
Best when you want to insert only if
Usage always update the
missing, ensuring no accidental
Scenario mapping regardless of its
overwrites.
previous state.
map.put(1, "Alice"); →
map.putIfAbsent(1, "Bob"); → inserts
Example overwrites value if key 1
only if key 1 has
exists.
Aspect HashMap Hashtable
Legacy class that also
Implements the Map interface; stores
Definition implements Map; stores
key–value pairs.
key–value pairs.
Synchronized → thread-
Thread- Not synchronized → not thread-safe by
safe, suitable for multi-
Safety default.
threaded use.
Allows one null key and multiple null Does not allow null keys
Null Handling
values. or null values.
Slower because all
Faster due to lack of synchronization
Performance methods are
overhead.
synchronized.
Legacy vs Part of the modern Collections Considered legacy,
Modern Framework (introduced in Java 1.2). introduced in Java 1.0.
Uses Iterator, which is fail-fast (throws Uses Enumerator, which
Iteration
ConcurrentModificationException). is not fail-fast.
Hashtable<Integer,
HashMap<Integer, String> map = new
Example String> table = new
HashMap<>();
Hashtable<>();
Aspect TreeMap Hashtable
Implements the NavigableMap
Legacy class implementing
interface; stores key–value pairs in
Definition Map; stores key–value pairs
sorted order (based on natural order
in unsorted order.
or a custom comparator).
Does not maintain any
Order Maintains sorted order of keys.
order.
Thread- Not synchronized → not thread-safe Synchronized → thread-
Safety by default. safe.
Does not allow null keys, but allows Does not allow null keys or
Null Handling
multiple null values. null values.
Operations like get(), put(),
Operations like get(), put(), remove()
Performance remove() take O(1) on
take O(log n) time (Red-Black tree).
average (hashing).
Legacy vs Part of modern Collections Legacy class, introduced in
Modern Framework. Java 1.0.
Suitable for thread-safe
Usage Suitable when sorted key traversal is
key–value storage without
Scenario required.
ordering concern.
TreeMap<Integer, String> map = new Hashtable<Integer, String>
Example
TreeMap<>(); table = new Hashtable<>();
Aspect Properties Hashtable
A legacy class implementing
A subclass of Hashtable used to maintain
the Map interface; stores
Definition key–value pairs of strings (mainly for
key–value pairs of any
configuration or property files).
object type.
Both keys and values are Strings
Key/Value Keys and values can be any
(enforced, though technically it inherits
Type object.
Object).
Specifically designed for reading/writing General-purpose key–value
Purpose configuration files using .properties storage for any type of
files. objects.
Null Does not allow null keys or null Does not allow null keys or
Handling values. null values.
Thread- Synchronized → thread-safe (inherits Synchronized → thread-
Safety from Hashtable). safe.
Provides additional methods like Does not provide file I/O
Usage
load(InputStream in), store(OutputStream methods; general-purpose
Methods
out, String comments). map operations only.
Hashtable<Integer, String>
Properties prop = new Properties();
Example table = new Hashtable<>();
prop.setProperty("username", "admin");
table.put(1, "Alice");
Aspect EnumSet EnumMap
A specialized Set implementation A specialized Map implementation
Definition
for use with enum types. for use with enum keys.
Stores unique enum constants Maps enum keys to
Purpose
efficiently. corresponding values efficiently.
Internally backed by an array,
Underlying Internally backed by bit vectors,
ordered according to enum
Structure very memory-efficient.
declaration.
Does not allow null keys; values
Null Handling Does not allow null elements.
can be null.
Maintains natural order of enum Maintains keys in natural order
Order
constants. of enum constants.
Very fast operations (add, Very fast operations (get, put,
Performance remove, contains) due to bitwise remove) due to array-based
representation. storage.
EnumSet<Day> days = EnumMap<Day, String> map =
Usage
EnumSet.of(Day.MONDAY, new EnumMap<>(Day.class);
Example
Day.WEDNESDAY); map.put(Day.MONDAY, "Work");
Aspect HashMap WeakHashMap
A standard Map A Map implementation where keys are
implementation that stores stored as weak references, allowing
Definition
key–value pairs and allows garbage collection when no strong
strong references to keys. references exist.
Uses strong references;
Uses weak references; keys can be
Key keys are not garbage
garbage collected if no external strong
Reference collected as long as the map
references exist.
exists.
Keys can be automatically removed by
Garbage Keys and values are retained
garbage collector when they become
Collection until explicitly removed.
weakly reachable.
Allows one null key and Allows one null key and multiple null
Null Handling
multiple null values. values.
Suitable for general-purpose Suitable for caching, listeners, or
Use Case key–value storage where temporary mappings where keys
keys must be retained. should not prevent GC.
Slightly overhead due to reference
Standard performance, O(1)
Performance queue processing, but similar average
average for get/put/remove.
performance.
HashMap<Integer, String> WeakHashMap<Integer, String> map
Example
map = new HashMap<>(); = new WeakHashMap<>();
Aspect HashMap ConcurrentHashMap
A standard Map implementation
A thread-safe Map implementation
Definition for storing key–value pairs; not
designed for concurrent access.
thread-safe.
Synchronized internally using
Thread- Not synchronized → not safe for
segment-level locking (Java 8+
Safety multi-threaded access.
uses CAS and bin-level locking).
Null Allows one null key and multiple Does not allow null keys or null
Handling null values. values.
Faster in single-threaded Slightly slower in single-threaded
Performance scenarios due to no scenarios but efficient in multi-
synchronization overhead. threaded environments.
Uses weakly consistent Iterator;
Uses fail-fast Iterator; throws does not throw
Iteration ConcurrentModificationException ConcurrentModificationException
if modified during iteration. and reflects some changes during
iteration.
Suitable for single-threaded Suitable for highly concurrent
Use Case applications or externally environments where multiple
synchronized maps. threads read/write frequently.
ConcurrentHashMap<Integer,
HashMap<Integer, String> map =
Example String> map = new
new HashMap<>();
ConcurrentHashMap<>();
Aspect CopyOnWriteArrayList CopyOnWriteArraySet
A thread-safe variant of ArrayList A thread-safe variant of Set
where all mutative operations backed by a
Definition
(add, set, remove) create a new CopyOnWriteArrayList; maintains
copy of the underlying array. unique elements.
Allows duplicate elements like a Does not allow duplicates; each
Duplicates
normal List. element must be unique.
Maintains insertion order of Maintains insertion order of
Order
elements. elements.
Allows null elements (since
Null
Allows null elements. internally backed by
Handling
CopyOnWriteArrayList).
Thread- Thread-safe for concurrent read Thread-safe for concurrent read
Safety and write operations. and write operations.
Efficient for many reads and few
Efficient for many reads and few
writes; writes are expensive due
Performance writes; writes are expensive due
to array copying and uniqueness
to copying the array.
checks.
CopyOnWriteArraySet<String>
Usage CopyOnWriteArrayList<String> list
set = new
Example = new CopyOnWriteArrayList<>();
CopyOnWriteArraySet<>();
Aspect Queue SynchronousQueue
A collection used to store
A special blocking queue where each
elements in FIFO (First-In-First-
insert operation (put) must wait for a
Definition Out) order; allows insertion,
corresponding remove operation
removal, and inspection of
(take) by another thread.
elements.
Can be bounded or
unbounded depending on Has zero capacity; does not store
Capacity
implementation (LinkedList, elements internally.
ArrayDeque, PriorityQueue).
Maintains element order (FIFO
Does not maintain any order; only
for most implementations;
Order acts as a handoff between producer
PriorityQueue uses priority
and consumer.
order).
Most queues are non-blocking;
Blocking Always blocking; put() waits for
some blocking variants exist
Behavior take() and vice versa.
(LinkedBlockingQueue).
Depends on implementation: Thread-safe by design; intended for
Thread-
ConcurrentLinkedQueue is synchronous handoff between
Safety
thread-safe, LinkedList is not. threads.
Suitable for general-purpose Suitable for direct handoff scenarios
Use Case queuing (task scheduling, where producer and consumer must
buffering). rendezvous.
SynchronousQueue<Integer> sq =
Queue<Integer> q = new
Example new SynchronousQueue<>();
LinkedList<>(); q.add(1);
sq.put(1);
Aspect Queue PriorityQueue
A collection used to store A special type of queue where
Definition elements in FIFO (First-In- elements are ordered based on
First-Out) order. priority, not insertion order.
Maintains insertion order Maintains elements in natural
Order for most implementations ordering or according to a custom
(e.g., LinkedList). comparator.
Duplicates Allows duplicates. Allows duplicates.
Usually allows a single null
Null
in some implementations Does not allow null elements.
Handling
(like LinkedList).
Underlying Depends on implementation:
Internally backed by a binary heap.
Structure LinkedList, ArrayDeque, etc.
add(), offer(), poll(), peek(); always
Access add(), offer(), poll(), peek();
returns the smallest (or highest-
Operations first-in-first-out order.
priority) element first.
Suitable for simple queuing Suitable for priority-based
Use Case tasks like task scheduling in processing, e.g., job scheduling or
FIFO order. event handling.
Queue<Integer> q = new PriorityQueue<Integer> pq = new
Example
LinkedList<>(); q.add(5); PriorityQueue<>(); pq.add(5);
Aspect Hashtable ConcurrentHashMap
Legacy class
implementing the Map
Modern thread-safe Map implementation
Definition interface; thread-safe
optimized for concurrent access.
using synchronized
methods.
Synchronized on all
Uses segment-level locking / CAS
Thread- methods, which can lead
(Java 8+: finer-grained locking), allowing
Safety to bottlenecks in high
better concurrency.
concurrency.
Null Does not allow null keys Does not allow null keys or null
Handling or null values. values.
Slower in multi-threaded
Faster in concurrent environments due to
Performance environments due to
fine-grained locking.
coarse-grained locking.
Uses weakly consistent Iterator; does
Uses Enumerator or
not throw
Iteration Iterator; fail-safe behavior
ConcurrentModificationException and
is limited.
reflects some updates.
Legacy vs Legacy class, introduced Part of the modern java.util.concurrent
Modern in Java 1.0. package.
Suitable for legacy
Suitable for highly concurrent
Usage applications requiring
applications with frequent read/write
Scenario thread-safe key–value
operations.
storage.
Hashtable<Integer,
ConcurrentHashMap<Integer, String>
Example String> table = new
map = new ConcurrentHashMap<>();
Hashtable<>();
Aspect ArrayList CopyOnWriteArrayList
A thread-safe variant of ArrayList
A resizable array implementation where all mutative operations
Definition
of List, not thread-safe. create a new copy of the
underlying array.
Thread-safe → suitable for
Thread- Not synchronized → not safe
concurrent read and write
Safety for concurrent access.
operations.
Fast for single-threaded
Fast for read-heavy scenarios, but
Performanc read/write operations;
writes (add/remove/set) are
e standard add, remove, get are
expensive due to array copying.
efficient.
Uses snapshot-style iterator; does
Uses fail-fast iterator; throws
Iterator not throw
ConcurrentModificationExceptio
Behavior ConcurrentModificationException
n if modified during iteration.
, reads see a consistent snapshot.
Uses more memory because each
Memory Uses memory efficiently; only
modification creates a new copy of
Usage one underlying array.
the array.
Suitable for read-mostly, multi-
Suitable for normal lists in
threaded contexts where thread
Use Case single-threaded or externally
safety is required without external
synchronized contexts.
synchronization.
ArrayList<String> list = new CopyOnWriteArrayList<String> list =
Example
ArrayList<>(); new CopyOnWriteArrayList<>();