Posts

Showing posts with the label Java Collections

Internal working of ArrayList: Source Code, Examples, and Practical Insights

Image
Introduction In Java, collections are essential for handling dynamic data where the size of elements isn’t fixed at compile time. Arrays provide constant-time access, but they come with a limitation: fixed size. Once declared, the size of an array cannot be changed. That’s where ArrayList comes in — it combines the benefits of arrays (random access) with the flexibility of dynamic resizing. ArrayList is one of the most widely used classes in the Java Collections Framework (JCF) . It is part of the java.util package and is ideal for scenarios where frequent retrieval operations are more common than frequent insertions or deletions in the middle of the list. ArrayList Hierarchy in Collections Framework Here’s how ArrayList fits into the JCF hierarchy: java.lang.Object ↳ java.util.AbstractCollection<E> ↳ java.util.AbstractList<E> ↳ java.util.ArrayList<E> ArrayList implements List , RandomAccess , Cloneable , and Serializable . Array...

ConcurrentHashMap vs Synchronized HashMap in Java

Image
Introduction In multi-threaded Java applications, managing shared data safely and efficiently is crucial. Two common approaches are using Synchronized HashMap (via Collections.synchronizedMap(...) ) and ConcurrentHashMap . While both aim to provide thread-safety, their implementations and performance characteristics differ significantly. This post explores these differences in detail. What is a Synchronized HashMap? Created by wrapping a regular HashMap using: Map<K, V> syncMap = Collections.synchronizedMap(new HashMap<>()); Enforces synchronization at the object level , meaning only one thread can access the map at any time (read or write). Supports null keys and values since it relies on HashMap behavior. Iterators are fail-fast , throwing ConcurrentModificationException if the map is modified while iterating. Simpler implementation, suitable when concurrency is low or performance is not cri...