JCF gives you ready-made ways to store and manage collections (groups) of objects. It includes rules (interfaces), actual tools (classes), helpful methods (algorithms), and extra helpers.
Collection
interface: For most collections (not maps)Map
interface: For key-value pairsInterfaces define what you can do with collections. They build on each other.
What it is: The main blueprint for groups of items (elements). No order or no duplicates guaranteed here.
add(E item)
: Put in a new item. Returns true if addedaddAll(Collection other)
: Add everything from another groupremove(Object item)
: Take out the first matching itemremoveAll(Collection other)
: Remove all items that are in the other groupretainAll(Collection other)
: Keep only items that are in both (like overlap)
contains(Object item)
: Check if item is there (true/false)size()
: How many itemsisEmpty()
: True if nothing insideclear()
: Empty it alliterator()
: Get a tool to loop through itemstoArray()
: Turn into a plain arrayExplanation: This is basic for all non-map collections. It lets you add/remove/check without caring about order.
What it is: An ordered group where duplicates are okay. You can access by position (index, starting from 0).
get(int index)
: Get item at positionset(int index, E item)
: Change item at positionadd(int index, E item)
: Insert at specific spotremove(int index)
: Remove from positionindexOf(Object item)
: Find first position of item (-1 if not found)lastIndexOf(Object item)
: Find last positionsubList(int start, int end)
: Get a part of the list as a viewlistIterator()
: Tool to go forward/backwardExplanation: Good when order matters, like a to-do list. You can insert anywhere, but it might shift items.
What it is: Group with no duplicates. No fixed order.
Actions: Same as Collection, but add won't add if already there (returns false).
Explanation: Uses equals() and hashCode() to check uniqueness. Great for unique items like IDs.
first()
(smallest), last()
(biggest),
headSet(E to)
, tailSet(E from)
lower(E item)
(just below), floor(E item)
,
ceiling(E item)
, higher(E item)
What it is: Group for waiting items, usually first-in-first-out (FIFO, like a line).
offer(E item)
: Add if possible (false if full)poll()
: Remove and get first (null if empty)remove()
: Remove first (error if empty)peek()
: See first without removing (null if empty)element()
: See first (error if empty)Explanation: For tasks in order, like printing jobs.
Sub-Blueprint: Deque (Double-ended queue): Add/remove from both ends. Can act as stack (last-in-first-out, LIFO).
What it is: A thread-safe queue used in concurrent programming. If queue is full, producer threads wait; if empty, consumer threads wait.
put(E item)
: Waits if queue is full before inserting.take()
: Waits if queue is empty before removing.offer(E item, long timeout, TimeUnit unit)
: Adds item, waits for space if
needed.poll(long timeout, TimeUnit unit)
: Removes item, waits if empty.Common Implementations: ArrayBlockingQueue
,
LinkedBlockingQueue
,
PriorityBlockingQueue
.
What it is: Not from Collection. Stores pairs: key (unique) and value.
put(K key, V value)
: Add or update pairget(Object key)
: Get value for key (null if none)remove(Object key)
: Remove paircontainsKey(Object key)
, containsValue(Object value)
keySet()
: Get all keys as Setvalues()
: Get all values as CollectionentrySet()
: Get pairs as Set of entriesputAll(Map other)
: Add from another mapsize()
, isEmpty()
, clear()
Explanation: Like a dictionary: key is word, value is meaning. Keys can't repeat.
These are the actual tools you use. Here are the main classes organized by type:
Class Name | What It Does | Speed (Key Actions) | When to Use | Thread Safe? |
---|---|---|---|---|
ArrayList | Growable array. Fast to get by index. | Get/Set: Fast (O(1)) Add/Remove end: Fast Add/Remove middle: Slow (O(n)) |
Everyday lists, quick access | No |
LinkedList | Chain of links. Implements List and Deque. | Get/Set: Slow (O(n)) Add/Remove ends: Fast (O(1)) |
Add/remove often at ends (queues) | No |
Vector | Old version of ArrayList, but safe for threads. | Like ArrayList, but slower | Old code or simple thread safety | Yes |
Stack | Builds on Vector, for stacks (LIFO). | Push/Pop: Fast | Stacks, but better use Deque now | Yes |
Class Name | What It Does | Speed | When to Use | Thread Safe? |
---|---|---|---|---|
HashSet | Uses hash for no order. | Add/Remove/Check: Fast (O(1) average) | Quick unique checks, no order | No |
LinkedHashSet | Like HashSet, but remembers add order. | Like HashSet | Unique with order | No |
TreeSet | Sorted tree. | Add/Remove/Check: O(log n) | Sorted uniques. Needs sort rule. | No |
EnumSet | For enum types, very fast. | All: O(1) | Sets of enums | No |
Class Name | What It Does | Speed | When to Use | Thread Safe? |
---|---|---|---|---|
ArrayDeque | Growable array for both ends. Faster than LinkedList. | Add/Remove: Fast (O(1)) | Queues or stacks | No |
LinkedList | As above. | Ends: Fast | Queues | No |
PriorityQueue | Heap for priorities (not fully sorted). | Add/Remove: O(log n) Peek: O(1) |
Tasks by importance | No |
ConcurrentLinkedQueue | Thread-safe unlimited queue. | O(1) | Multi-thread queues | Yes |
Class Name | What It Does | Speed | When to Use | Thread Safe? |
---|---|---|---|---|
HashMap | Hash table, allows null. No order. | Put/Get/Remove: O(1) average | Everyday maps | No |
LinkedHashMap | Like HashMap, tracks order (add or access). | Like HashMap | Order matters, like caches | No |
TreeMap | Sorted tree for keys. | O(log n) | Sorted maps | No |
Hashtable | Old, thread-safe, no null. | Like HashMap, slower | Old code | Yes |
ConcurrentHashMap | Thread-safe, fast for many users. | O(1) | Multi-thread maps | Yes |
iterator()
to go through items one by one.
hasNext()
(more items?), next()
(get next),
remove()
(delete last got)
remove()
)
hasPrevious()
, previous()
, add()
,
set()
Streams
APItrySplit()
, forEachRemaining()
for (String s : list)
ConcurrentModificationException
if
collection is modified (e.g., ArrayList
, HashSet
).CopyOnWriteArrayList
, ConcurrentHashMap
).
int compareTo(T o)
β returns negative, zero, or positive.
int compare(T o1, T o2)
.
import java.util.*; // β Example 1: Using Comparable (natural order) class Student implements Comparable{ int id; String name; Student(int id, String name) { this.id = id; this.name = name; } // Natural order: by id (ascending) public int compareTo(Student other) { return this.id - other.id; } public String toString() { return id + "-" + name; } } // β Example 2: Using Comparator (custom order) class NameComparator implements Comparator { public int compare(Student s1, Student s2) { return s1.name.compareTo(s2.name); // sort by name } } public class Main { public static void main(String[] args) { List list = new ArrayList<>(); list.add(new Student(3, "Deepak")); list.add(new Student(1, "Tushar")); list.add(new Student(2, "Shreeram")); // πΉ Natural sort (Comparable β by id) Collections.sort(list); System.out.println("Sorted by ID (Comparable): " + list); // πΉ Custom sort (Comparator β by name) Collections.sort(list, new NameComparator()); System.out.println("Sorted by Name (Comparator): " + list); // πΉ Even shorter using lambda Comparator list.sort((a, b) -> b.id - a.id); System.out.println("Sorted by ID Desc (Lambda Comparator): " + list); } }
Static helpers:
sort(List list)
: Sort naturallysort(List list, Comparator c)
: Custom sortbinarySearch(List list, Object key)
: Find in sorted listreverse(List)
, shuffle(List)
, swap(List, i, j)
unmodifiableCollection(Collection c)
: Make read-onlysynchronizedCollection(Collection c)
: Make thread-safecheckedCollection(Collection c, Class type)
: Extra type checksemptyList()
, singleton(item)
: Small fixed collectionsFor plain arrays:
sort(array)
, binarySearch(array, key)
asList(items...)
: Turn array to list (fixed size)fill(array, value)
, copyOf(array, length)
List list = new ArrayList();
β
can mix types, errors at run timeList<String> list = new ArrayList<>();
β Only
strings, checks at compile?
(any), ? extends Type
(subtypes),
? super Type
(supertypes) for flexibility
ArrayList
, HashMap
,
HashSet
) are not thread-safe. If multiple threads update them at the same time,
you can get data corruption or ConcurrentModificationException
.
Collections.synchronizedXXX()
to make existing collections thread-safe.Collections.synchronizedList(new ArrayList<>())
Meaning of XXX
java.util.concurrent
are designed for multi-threading.ConcurrentHashMap
: Thread-safe HashMap (no full lock, faster)CopyOnWriteArrayList
: Thread-safe List (good for more reads than writes)CopyOnWriteArraySet
: Thread-safe SetBlockingQueue
(e.g., ArrayBlockingQueue, LinkedBlockingQueue):
For producer-consumer pattern
- Use synchronized wrappers for small, simple multi-threaded tasks.
- Use concurrent collections for servers, thread pools, or real-time systems where
many threads read/write data at the same time.
- Fail-Fast Iterators throw errors if modified during iteration, while
Fail-Safe Iterators (in concurrent collections) work on a snapshot and donβt throw errors.
// β Example 1: Synchronized Map import java.util.*; public class Main { public static void main(String[] args) { Map<String, String> safeMap = Collections.synchronizedMap(new HashMap<>()); safeMap.put("A", "Apple"); safeMap.put("B", "Banana"); synchronized (safeMap) { // Must lock while iterating for (String key : safeMap.keySet()) { System.out.println(key + " β " + safeMap.get(key)); } } } }
// β Example 2: ConcurrentHashMap (no need to lock manually) import java.util.concurrent.*; public class Main { public static void main(String[] args) { ConcurrentHashMap<Integer, String> cmap = new ConcurrentHashMap<>(); cmap.put(1, "Deepak"); cmap.put(2, "Shreeram"); cmap.put(3, "Tushar"); // Multiple threads can safely access without explicit sync cmap.forEach((id, name) -> System.out.println(id + " β " + name)); } }
// β Example 3: CopyOnWriteArrayList (safe iteration even with updates) import java.util.concurrent.*; import java.util.*; public class Main { public static void main(String[] args) { CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>(); list.add("A"); list.add("B"); list.add("C"); for (String s : list) { System.out.println(s); list.add("D"); // No error, works safely } System.out.println("Final List: " + list); } }
keySet()
is live β changes affect mapnew HashMap(100)
to avoid growingAnswer: List: Ordered, duplicates ok. Set: No duplicates, no order (usually). Map: Key-value, unique keys.
Answer: ArrayList: Fast get by index. LinkedList: Fast add/remove at ends.
Answer: Uses hash to find bucket, handles collisions with lists/trees.
Answer: Throws error if collection changes during loop.
Answer: Add type like <String> for safety.
Answer: Use synchronized wrapper or concurrent classes.
Answer: Comparable: In class itself. Comparator: Separate for custom.
Answer: Heap for min/max priority.
Answer: Collections.sort(list).
Answer: Live subsets that change with map.