0% found this document useful (0 votes)
5 views27 pages

Collection Difference

The document compares various Java collection interfaces and classes, including Iterable, Iterator, List, Set, and Map implementations. It details their definitions, methods, performance, and usage scenarios, highlighting the differences between data structures like ArrayList, LinkedList, HashSet, and TreeSet. Additionally, it discusses interfaces such as Comparable and Comparator for object ordering, and methods for managing key-value pairs in HashMap and related classes.

Uploaded by

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

Collection Difference

The document compares various Java collection interfaces and classes, including Iterable, Iterator, List, Set, and Map implementations. It details their definitions, methods, performance, and usage scenarios, highlighting the differences between data structures like ArrayList, LinkedList, HashSet, and TreeSet. Additionally, it discusses interfaces such as Comparable and Comparator for object ordering, and methods for managing key-value pairs in HashMap and related classes.

Uploaded by

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

Aspect Iterable Iterator

An interface that An object that provides


represents a collection methods to iterate through
Definition
of elements that can elements of a collection
be traversed. one by one.
Defines the method Provides hasNext(), next(),
Methods iterator() which returns and remove() for traversal
an Iterator. and modification.
Used explicitly when step-
Used in enhanced for-
by-step traversal or
Usage each loop to iterate
removal of elements is
over a collection.
required.
Works at the collection Works at the element
Level of
level, declaring it can level, giving sequential
Abstraction
be iterated. access to elements.
An Iterator is obtained
An Iterable produces
Relationshi from an Iterable and
an Iterator for
p cannot exist
traversal.
independently.
List<String> list = Iterator<String> it =
Example new ArrayList<>(); → list.iterator(); → it is the
list is Iterable. Iterator.
Aspect Array ArrayList
A fixed-size data
A resizable class from the
structure used to
Definition java.util package that
store elements of the
implements List interface.
same 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 Can only store objects.
Data Types primitive types (e.g., Primitives must be wrapped
int, char) and objects. (e.g., int → Integer).
Provides faster access
Slightly slower than arrays
Performan (direct index-based
because it involves method
ce access using
calls and resizing overhead.
array[index]).

Less flexible;
operations like More flexible; provides
insertion and built-in methods like
Flexibility
deletion are add(), remove(),
difficult and contains(), etc.
manual.
int[] arr = new ArrayList<Integer> list
Usage
int[5]; → Array of = new ArrayList<>(); →
Example
integers. Dynamic list of integers.
Aspect Enumeration Iterator ListIterator
Modern
Legacy interface for Advanced
interface for
iterating over iterator that
iterating over
Definition collections, mainly allows
collections in
Vector and bidirectional
forward
Hashtable. traversal of List.
direction.
Direction Both forward
Only forward Only forward
of and backward
direction. direction.
Traversal directions.
hasNext(),
next(),
hasNext(),
hasMoreElements(), hasPrevious(),
Methods next(),
nextElement(). previous(),
remove().
add(), set(),
remove().
Can remove Can add,
Element Cannot modify
elements remove, and
Modificati collection elements
while modify elements
on while traversing.
iterating. during traversal.
Works only with
Works with
Applicable Works with legacy List
all Collection
Collection classes (Vector, implementations
classes (List,
s Stack, Hashtable). (ArrayList,
Set, Queue).
LinkedList).
Usage Enumeration e = Iterator it = ListIterator li =
Example v.elements(); list.iterator(); list.listIterator();
Aspect Enumeration Iterator ListIterator

Aspect List Set


An ordered
An unordered collection that
collection that
Definition does not allow duplicate
allows duplicate
elements.
elements.
Does not guarantee order
Maintains insertion
(except LinkedHashSet
order (elements are
Order maintains insertion order, and
stored in the order
TreeSet maintains sorted
they were added).
order).
Allows duplicates; Does not allow duplicates; if a
Duplicates multiple identical duplicate is added, it is
elements can exist. ignored.
Provides index-
Does not support index-based
Access by based access (e.g.,
access, elements are
Index list.get(0) to access
accessed via iteration.
first element).
Slightly slower for
Generally faster for search
search operations
Performan operations because of
compared to Set
ce hashing (HashSet) or sorting
(especially large
(TreeSet).
lists).
ArrayList, LinkedList, HashSet, LinkedHashSet,
Examples
Vector, Stack. TreeSet.
Aspect AbstractList ArrayList

A skeletal (abstract) A concrete, resizable


implementation of the List array-based
Definition interface that provides a implementation of the List
framework for creating interface built on top of
custom list implementations. AbstractList.

Abstract class (cannot be Concrete class (can be


Type
instantiated directly). instantiated directly).

Provides partial
Provides a ready-to-use
implementation of List so that
dynamic array that can
Purpose subclasses only need to
grow or shrink
implement core methods
automatically.
(get() and size()).

Meant to be extended by Already fully


Implementatio
developers to create custom implemented; no need for
n
list implementations with additional implementation
Responsibility
specific behavior. for standard usage.

Offers flexibility for creating Limited to array-backed


Flexibility tailored list types by list functionality; behavior
overriding methods. is predefined.

class MyList extends ArrayList<String> list =


Example Usage
AbstractList { ... } new ArrayList<>();
Aspect Vector ArrayList

A legacy class in
A modern resizable array
java.util package that
implementation of the List interface,
Definition implements a dynamic
introduced in Java 1.2 (Collections
array, introduced in
Framework).
Java 1.0.

Synchronized → thread- Not synchronized → faster but not


Thread- safe but slower in thread-safe (must use
Safety single-threaded Collections.synchronizedList() for
applications. thread safety).

Slower due to
Performan Faster as it does not have
synchronization
ce synchronization overhead.
overhead.

Doubles its size when Increases capacity by 50% when full


Growth
capacity is exceeded. (default behavior).

Considered a legacy Part of the Collections Framework,


Legacy vs
class, retained for widely preferred in modern
Modern
backward compatibility. applications.

Usage Vector<Integer> v = ArrayList<Integer> list = new


Example new Vector<>(); ArrayList<>();
Aspect ArrayList LinkedList

A resizable array A doubly linked list


Definition implementation of the List implementation of the List and
interface. Deque interfaces.

Uses a doubly linked list where


Underlying
Uses a dynamic array to each node holds data and
Data
store elements. references to next and previous
Structure
nodes.

Provides fast random


Access is slower (O(n)) because
Access (get access (O(1)) since
traversal is needed from the
/ set) elements are stored in a
head or tail.
contiguous array.

Insertion and deletion are


Insertion and deletion are faster
Insertion / slow (O(n)) in the middle
(O(1)) if position is known (just
Deletion due to shifting of
relinking nodes).
elements.

Consumes less memory Consumes more memory


Memory
since only data is stored in because each node stores extra
Usage
the array. references (previous and next).

Suitable when frequent Suitable when frequent


Best Use
retrieval operations are insertions/deletions occur in
Case
needed. the middle of the list.
Aspect HashSet TreeSet

Implements the Set


Implements the Set interface
interface using a hash
Definition using a TreeMap (Red-Black
table (backed by
Tree).
HashMap).

Does not guarantee Maintains elements in sorted


order of elements (ascending) order according to
Order
(insertion order not natural ordering or a custom
preserved). Comparator.

Offers constant time


Offers logarithmic time O(log
Performan O(1) for add, remove, and
n) for add, remove, and search
ce search operations on
operations.
average.

Null Does not allow null elements


Allows one null element.
Elements (throws NullPointerException).

Preferred when fast Preferred when sorted data is


Usage
lookups and no ordering needed while maintaining
Scenario
are required. uniqueness.

HashSet<Integer> hs = TreeSet<Integer> ts = new


Example
new HashSet<>(); TreeSet<>();
Aspect HashSet LinkedHashSet

Implements the Set interface Subclass of HashSet that uses


Definition using a hash table (backed a linked list + hash table
by HashMap). combination.

Does not maintain any Maintains insertion order of


Order
order of elements. elements.

Provides constant-time O(1) Slightly slower than HashSet


Performan
performance for add, remove, due to maintaining a linked
ce
and search (on average). list, but still O(1) on average.

Null Also allows one null


Allows one null element.
Elements element.

Requires more memory


Memory Requires less memory as only
because it maintains a linked
Usage hashing is maintained.
list in addition to hashing.

Suitable when only Suitable when uniqueness


Usage uniqueness and fast with predictable iteration
Scenario performance are needed order (insertion order) is
without caring about order. required.
Aspect LinkedHashMap Set

A Map implementation that


A Collection that stores only
Definitio stores key–value pairs and
unique elements and does
n maintains insertion order (or
not allow duplicates.
access order if specified).

Implemented using various


Data Based on hash table + doubly data structures like HashSet
Structur linked list (for order (hash table), LinkedHashSet
e maintenance). (hash table + linked list), or
TreeSet (red-black tree).

Stores key–value pairs (e.g.,


key → value). Keys must be Stores only elements (no
Storage
unique, but values can be key–value mapping).
duplicated.

Order depends on
Maintains insertion order (or implementation: HashSet (no
Order access order with order), LinkedHashSet
accessOrder=true). (insertion order), TreeSet
(sorted order).

Allows one null element (in


Null Allows one null key and
HashSet / LinkedHashSet), but
Handling multiple null values.
TreeSet does not allow null.

Used when you only need a


Used when you need to maintain
Usage unique collection of
a mapping of keys to values
Scenario elements without key–value
with predictable iteration order.
mapping.

LinkedHashMap<Integer,
Set<Integer> set = new
Example String> map = new
HashSet<>();
LinkedHashMap<>();
Aspect Comparable Comparator

An interface used to
An interface used to define
Definition define the natural
custom ordering of objects.
ordering of 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 only one Supports multiple sorting


Sorting sorting sequence sequences (different
Sequences (natural ordering). comparators can be created).

Class must implement


No modification of the original
Comparable, so
Modification class is required; separate
modification of the class is
s comparator classes can be
required to define
created.
ordering.

Best when objects have a Best when different custom


Usage default, natural order sort orders are needed (e.g.,
Scenario (e.g., sorting numbers, sorting employees by name,
strings). then by salary).

class Student implements


Comparable<Student> Comparator<Student> byName
Example { public int = (s1, s2) ->
compareTo(Student s) s1.name.compareTo(s2.name);
{ return this.id - s.id; } }
Aspect HashSet HashMap

Implements the Set interface


Implements the Map interface
Definition and stores unique elements
and stores key–value pairs.
only.

Internally uses a HashMap


Data Uses a hash table to store
(elements are stored as keys
Structure key–value mappings.
with a dummy value).

Does not allow duplicate


Duplicate Does not allow duplicate
keys, but values can be
s elements.
duplicated.

Null Allows one null key and


Allows one null element.
Handling multiple null values.

Does not guarantee order Does not guarantee order of


Order (insertion order not keys/values (unless using
preserved). LinkedHashMap).

Suitable when only unique Suitable when you need to


Usage
elements are needed without associate keys with values
Scenario
mapping. (like a dictionary).

HashSet<String> set = new HashMap<Integer, String>


Example
HashSet<>(); map = new HashMap<>();
Aspect Iterator ListIterator

An interface used to
traverse elements of any A bidirectional iterator used to
Definition
Collection (like Set, List, traverse elements of a List only.
Queue).

Direction of Traverses in forward Traverses in both forward and


Traversal direction only. backward directions.

Can be used with all Can be used only with List


Applicable
Collection classes (Set, List, implementations (ArrayList,
Collections
Queue). LinkedList, etc.).

hasNext(), next(), hasPrevious(),


Methods
hasNext(), next(), remove(). previous(), add(), remove(),
Provided
set().

Provides index information


Index Does not provide index of
using nextIndex() and
Access elements during traversal.
previousIndex().

Best for more complex


Best for simple, forward-
Usage traversals where both
only iteration over a
Scenario directions and modifications are
collection.
needed.

Iterator<String> it = ListIterator<String> li =
Example
list.iterator(); list.listIterator();
Aspect containsKey(Object key) containsValue(Object value)

Checks if the specified key Checks if the specified value is


Definition
is present in the map. present in the map.

Returns true if the map


Return Returns true if the map contains
contains the given key, else
Type the given value, else false.
false.

Looks up based on keys Looks up based on values


Search
(fast, usually O(1) in (slower, O(n) as it may scan all
Basis
HashMap). entries).

More efficient because map


Performan Less efficient since it requires
implementations are
ce checking each entry's value.
optimized for key lookups.

Works even if the key is null Works if the value is null


Null
(allowed only one null key in (multiple null values allowed in
Handling
HashMap). HashMap).

Used to verify the existence Used when you need to check if


Usage
of a mapping key before a particular value is mapped
Scenario
accessing or inserting. to by any key.

map.containsValue("Alice") →
map.containsKey(101) →
Example checks if "Alice" exists as a
checks if key 101 exists.
value.
Aspect put(K key, V value) putIfAbsent(K key, V value)

Inserts the mapping only if the key


Inserts or updates the
is not already associated with a
Definition mapping of a key to a
value (i.e., absent or mapped to
value.
null).

If the key already exists,


If the key already exists with a non-
Overwritin the old value is
null value, the existing value is
g Behavior replaced with the new
retained (no overwrite).
value.

Returns the previous Returns the existing value if the


Return
value associated with key is present; otherwise, returns
Value
the key, or null if none. null after inserting.

Allows null key (in Works similarly, but if key exists


Null
HashMap) and multiple with null value, it will insert the new
Handling
null values. value.

Not inherently thread- Designed with concurrency in mind,


Thread- safe (in HashMap), but commonly used in
Safety available in concurrent ConcurrentHashMap to avoid race
maps too. conditions.

Best when you want to


Best when you want to insert only
Usage always update the
if missing, ensuring no accidental
Scenario mapping regardless of
overwrites.
its previous state.

map.put(1, "Alice"); →
map.putIfAbsent(1, "Bob"); →
Example overwrites value if key 1
inserts only if key 1 has
exists.
Aspect HashMap Hashtable

Legacy class that also


Implements the Map interface;
Definition implements Map; stores
stores key–value pairs.
key–value pairs.

Synchronized →
Thread- Not synchronized → not thread-
thread-safe, suitable
Safety safe by default.
for multi-threaded use.

Null Allows one null key and multiple Does not allow null
Handling null values. keys or null values.

Slower because all


Performan Faster due to lack of synchronization
methods are
ce overhead.
synchronized.

Part of the modern Collections


Legacy vs Considered legacy,
Framework (introduced in Java
Modern introduced in Java 1.0.
1.2).

Uses Iterator, which is fail-fast


Uses Enumerator,
Iteration (throws
which is not fail-fast.
ConcurrentModificationException).

Hashtable<Integer,
HashMap<Integer, String> map =
Example String> table = new
new HashMap<>();
Hashtable<>();
Aspect TreeMap Hashtable

Implements the NavigableMap


Legacy class
interface; stores key–value pairs
implementing Map; stores
Definition in sorted order (based on
key–value pairs in
natural order or a custom
unsorted order.
comparator).

Does not maintain any


Order Maintains sorted order of keys.
order.

Thread- Not synchronized → not thread- Synchronized → thread-


Safety safe by default. safe.

Null Does not allow null keys, but Does not allow null
Handling allows multiple null values. keys or null values.

Operations like get(), put(), Operations like get(),


Performan
remove() take O(log n) time put(), remove() take O(1)
ce
(Red-Black tree). on average (hashing).

Legacy vs Part of modern Collections Legacy class, introduced


Modern Framework. in Java 1.0.

Suitable for thread-safe


Usage Suitable when sorted key
key–value storage
Scenario traversal is required.
without ordering concern.
Aspect TreeMap Hashtable

Hashtable<Integer,
TreeMap<Integer, String> map =
Example String> table = new
new TreeMap<>();
Hashtable<>();

Aspect Properties Hashtable

A legacy class
A subclass of Hashtable used to
implementing the Map
Definitio maintain key–value pairs of
interface; stores key–
n strings (mainly for configuration or
value pairs of any
property files).
object type.

Key/ Both keys and values are Strings


Keys and values can be
Value (enforced, though technically it
any object.
Type inherits Object).

Specifically designed for General-purpose key–


Purpose reading/writing configuration value storage for any
files using .properties files. type of objects.

Null Does not allow null keys or null Does not allow null keys
Handling values. or null values.

Thread- Synchronized → thread-safe Synchronized → thread-


Safety (inherits from Hashtable). safe.

Provides additional methods like


Does not provide file I/O
Usage load(InputStream in),
methods; general-purpose
Methods store(OutputStream out, String
map operations only.
comments).

Example Properties prop = new Properties(); Hashtable<Integer,


prop.setProperty("username", String> table = new
"admin"); Hashtable<>();
Aspect Properties Hashtable

table.put(1, "Alice");

Aspect EnumSet EnumMap

A specialized Set A specialized Map


Definition implementation for use with implementation for use with
enum types. enum keys.

Maps enum keys to


Stores unique enum
Purpose corresponding values
constants efficiently.
efficiently.

Internally backed by bit Internally backed by an array,


Underlying
vectors, very memory- ordered according to enum
Structure
efficient. declaration.

Null Does not allow null Does not allow null keys;
Handling elements. values can be null.

Maintains natural order of Maintains keys in natural


Order
enum constants. order of enum constants.

Very fast operations (add, Very fast operations (get, put,


Performanc
remove, contains) due to remove) due to array-based
e
bitwise representation. storage.

EnumMap<Day, String> map


EnumSet<Day> days = = new
Usage
EnumSet.of(Day.MONDAY, EnumMap<>(Day.class);
Example
Day.WEDNESDAY); map.put(Day.MONDAY,
"Work");
Aspect HashMap WeakHashMap

A standard Map
A Map implementation where keys
implementation that
are stored as weak references,
Definition stores key–value pairs
allowing garbage collection when
and allows strong
no strong references exist.
references to keys.

Uses strong references;


Uses weak references; keys can
Key keys are not garbage
be garbage collected if no
Reference collected as long as the
external strong references exist.
map exists.

Keys can be automatically


Keys and values are
Garbage removed by garbage collector
retained until explicitly
Collection when they become weakly
removed.
reachable.

Null Allows one null key and Allows one null key and multiple
Handling multiple null values. null values.

Use Case Suitable for general- Suitable for caching, listeners,


purpose key–value or temporary mappings where
storage where keys must
Aspect HashMap WeakHashMap

be retained. keys should not prevent GC.

Standard performance, Slightly overhead due to reference


Performan
O(1) average for queue processing, but similar
ce
get/put/remove. average performance.

HashMap<Integer,
WeakHashMap<Integer, String>
Example String> map = new
map = new WeakHashMap<>();
HashMap<>();

Aspect HashMap ConcurrentHashMap

A standard Map
A thread-safe Map
implementation for storing
Definition implementation designed for
key–value pairs; not thread-
concurrent access.
safe.

Synchronized internally using


Thread- Not synchronized → not safe segment-level locking (Java
Safety for multi-threaded access. 8+ uses CAS and bin-level
locking).

Null Allows one null key and Does not allow null keys or
Handling multiple null values. null values.

Slightly slower in single-


Faster in single-threaded
Performan threaded scenarios but
scenarios due to no
ce efficient in multi-threaded
synchronization overhead.
environments.
Aspect HashMap ConcurrentHashMap

Uses weakly consistent


Uses fail-fast Iterator;
Iterator; does not throw
throws
Iteration ConcurrentModificationExcepti
ConcurrentModificationExcepti
on and reflects some changes
on if modified during iteration.
during iteration.

Suitable for highly


Suitable for single-threaded
concurrent environments
Use Case applications or externally
where multiple threads
synchronized maps.
read/write frequently.

ConcurrentHashMap<Integer,
HashMap<Integer, String>
Example String> map = new
map = new HashMap<>();
ConcurrentHashMap<>();

Aspect CopyOnWriteArrayList CopyOnWriteArraySet

A thread-safe variant of
A thread-safe variant of Set
ArrayList where all mutative
backed by a
Definition operations (add, set, remove)
CopyOnWriteArrayList;
create a new copy of the
maintains unique elements.
underlying array.

Does not allow duplicates;


Allows duplicate elements
Duplicates each element must be
like a normal List.
unique.

Maintains insertion order of Maintains insertion order of


Order
elements. elements.

Null Allows null elements. Allows null elements (since


Aspect CopyOnWriteArrayList CopyOnWriteArraySet

internally backed by
Handling
CopyOnWriteArrayList).

Thread- Thread-safe for concurrent Thread-safe for concurrent


Safety read and write operations. read and write operations.

Efficient for many reads and


Efficient for many reads and
few writes; writes are
Performan few writes; writes are
expensive due to array
ce expensive due to copying the
copying and uniqueness
array.
checks.

CopyOnWriteArrayList<String> CopyOnWriteArraySet<String
Usage
list = new > set = new
Example
CopyOnWriteArrayList<>(); CopyOnWriteArraySet<>();

Aspect Queue SynchronousQueue

A collection used to store A special blocking queue where


elements in FIFO (First-In- each insert operation (put) must
Definitio
First-Out) order; allows wait for a corresponding remove
n
insertion, removal, and operation (take) by another
inspection of elements. thread.

Can be bounded or
unbounded depending on Has zero capacity; does not
Capacity
implementation (LinkedList, store elements internally.
ArrayDeque, PriorityQueue).
Aspect Queue SynchronousQueue

Maintains element order


(FIFO for most Does not maintain any order;
Order implementations; only acts as a handoff between
PriorityQueue uses priority producer and consumer.
order).

Most queues are non-


Blocking blocking; some blocking Always blocking; put() waits for
Behavior variants exist take() and vice versa.
(LinkedBlockingQueue).

Depends on implementation: Thread-safe by design; intended


Thread-
ConcurrentLinkedQueue is for synchronous handoff
Safety
thread-safe, LinkedList is not. between threads.

Suitable for general- Suitable for direct handoff


Use
purpose queuing (task scenarios where producer and
Case
scheduling, buffering). consumer must 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- elements are ordered based on
In-First-Out) order. priority, not insertion order.

Order Maintains insertion Maintains elements in natural


order for most ordering or according to a
Aspect Queue PriorityQueue

implementations (e.g.,
custom comparator.
LinkedList).

Duplicates Allows duplicates. Allows duplicates.

Usually allows a single


Null null in some
Does not allow null elements.
Handling implementations (like
LinkedList).

Depends on
Underlying implementation: Internally backed by a binary
Structure LinkedList, ArrayDeque, heap.
etc.

add(), offer(), poll(), add(), offer(), poll(), peek(); always


Access
peek(); first-in-first-out returns the smallest (or
Operations
order. highest-priority) element first.

Suitable for simple Suitable for priority-based


Use Case queuing tasks like task processing, e.g., job scheduling
scheduling in FIFO order. or 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
Definition interface; thread-safe implementation optimized for
using synchronized concurrent access.
methods.

Synchronized on all
Uses segment-level locking / CAS
Thread- methods, which can
(Java 8+: finer-grained locking),
Safety lead to bottlenecks in
allowing better concurrency.
high concurrency.

Null Does not allow null Does not allow null keys or null
Handling keys or null values. values.

Slower in multi-
Performan threaded environments Faster in concurrent environments
ce due to coarse-grained due to fine-grained locking.
locking.

Uses weakly consistent Iterator;


Uses Enumerator or
does not throw
Iteration Iterator; fail-safe
ConcurrentModificationException and
behavior is limited.
reflects some updates.

Legacy vs Legacy class, Part of the modern


Modern introduced in Java 1.0. java.util.concurrent package.

Suitable for legacy


Suitable for highly concurrent
Usage applications requiring
applications with frequent
Scenario thread-safe key–value
read/write operations.
storage.

Hashtable<Integer, ConcurrentHashMap<Integer,
Example String> table = new String> map = new
Hashtable<>(); ConcurrentHashMap<>();
Aspect ArrayList CopyOnWriteArrayList

A thread-safe variant of
A resizable array
ArrayList where all mutative
Definition implementation of List, not
operations create a new
thread-safe.
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 read-heavy


Fast for single-threaded
scenarios, but writes
Performan read/write operations;
(add/remove/set) are
ce standard add, remove, get
expensive due to array
are efficient.
copying.

Uses fail-fast iterator; Uses snapshot-style iterator;


throws does not throw
Iterator
ConcurrentModificationExcep ConcurrentModificationExce
Behavior
tion if modified during ption, reads see a consistent
iteration. snapshot.

Uses more memory because


Memory Uses memory efficiently; only
each modification creates a
Usage one underlying array.
new copy of the array.

Suitable for read-mostly,


Suitable for normal lists in
multi-threaded contexts
single-threaded or
Use Case where thread safety is required
externally synchronized
without external
contexts.
synchronization.

CopyOnWriteArrayList<String>
ArrayList<String> list = new
Example list = new
ArrayList<>();
CopyOnWriteArrayList<>();

You might also like