c2cedge
C, Java & Python · C — Java Essentials

Java: Collections Framework

List, Set and Map — and choosing the right implementation — is bread-and-butter Java. The trade-offs between ArrayList, LinkedList, HashMap and TreeMap come up constantly.

Test weight: High (Java)Skill: Pick the right structureDifficulty: Medium

The Collections Framework gives you ready-made data structures behind three core interfaces: List (ordered, allows duplicates), Set (no duplicates), and Map (key–value pairs). Interviews focus on choosing the right implementation and knowing the performance trade-offs.

The three families and their choices

List: ArrayList (fast random access, slow middle inserts) vs LinkedList (fast inserts/removals, slow random access). Set: HashSet (unordered, O(1)) vs TreeSet (sorted, O(log n)). Map: HashMap (unordered, O(1)) vs TreeMap (sorted keys, O(log n)) vs LinkedHashMap (insertion order).

Using a List and a Map
List<String> names = new ArrayList<>();
names.add("Asha"); names.add("Ravi");

Map<String, Integer> ages = new HashMap<>();
ages.put("Asha", 30);
int a = ages.get("Asha");   // 30  (autounboxed)
⚡ The edge
  • ArrayList gives O(1) random access but O(n) inserts/removals in the middle; LinkedList is the opposite. Choose by your dominant operation — indexing vs frequent insertion/removal.
  • HashMap is unordered with average O(1) lookups; TreeMap keeps keys sorted with O(log n) operations. Use HashMap by default; TreeMap when you need sorted order; LinkedHashMap to preserve insertion order.
Worked example
When would you use ArrayList vs LinkedList?
  1. ArrayList is backed by a resizable array: fast O(1) get/set by index, but inserting/removing in the middle shifts elements (O(n)).
  2. LinkedList is a doubly-linked list: O(1) insert/remove at known positions, but O(n) to reach an index.
  3. Use ArrayList for mostly indexed access (the common case); LinkedList when you insert/remove frequently at the ends/known nodes.
Worked example
What's the difference between a HashSet and a HashMap?
  1. A HashMap stores key→value pairs and gives O(1) average lookup by key.
  2. A HashSet stores unique values only (no associated value) and is actually backed by a HashMap internally.
  3. Use a Map when you need values per key; a Set when you only need membership/uniqueness.
⚠ Watch out
  • HashMap/HashSet are unordered — don't rely on iteration order; use LinkedHashMap or TreeMap if order matters.
  • Modifying a collection while iterating it (without the iterator) throws ConcurrentModificationException.
  • Keys/elements in hash collections need correct hashCode() and equals() — custom objects without them misbehave.
Practice this — take a timed mock →
1,300+ questions, scored, with a weak-area report.
Know who's ready. Not who finished.
HomeLibraryPrivacyTerms