Common mistakes and practice
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
Most collection bugs come from a few habits: primitives or raw types in the brackets, treating a map like a list, calling methods the variable's type does not have, and picking the wrong family for the job.
Mistake 1: primitives and raw types
List<int> does not compile, because the type argument must be a class. Use the wrapper: List<Integer>, List<Double>, List<Character>, List<Boolean>.
Example 1 · Mistake: a raw list crashes at run time
import java.util.ArrayList;import java.util.List;
public class RawListDemo { public static void main(String[] args) { List marks = new ArrayList(); // raw type: no <Integer> marks.add(85); marks.add(92); marks.add("absent"); // the compiler cannot stop this
int total = 0; for (Object m : marks) { total = total + (Integer) m; } System.out.println("Total: " + total); }}Exception in thread "main" java.lang.ClassCastException: class java.lang.String cannot be cast to class java.lang.Integer (java.lang.String and java.lang.Integer are in module java.base of loader 'bootstrap') at RawListDemo.main(RawListDemo.java:13)
What this code does
- Without
<Integer>, the list holds plainObjects, so a String slips in and every read needs a cast. The crash comes only when the loop reaches"absent", on line 13. - This is the exact problem the Generics module solved. With
List<Integer> marks, the linemarks.add("absent")becomes a compile error and no cast is needed.
The opposite mistake is leaving the brackets out: List marks = new ArrayList();. This is a raw type. It compiles with only a warning, but every item becomes Object. Wrong values get in, every read needs a cast, and the error appears at run time as a ClassCastException.
javac prints "uses unchecked or unsafe operations", look for a missing <...>.Mistake 2: treating a map like a collection
A Map has no add, no get(int) and no for-each loop of its own. Pairs go in with put(key, value), values come out with get(key).
To loop, pick a view: keySet() for the keys, values() for the values. Then the for-each loop works as usual.
Example 2 · Looping over a map the right way
import java.util.Map;import java.util.TreeMap;
public class FeesLoopDemo { public static void main(String[] args) { Map<String, Integer> fees = new TreeMap<>(); fees.put("Tuition", 45000); fees.put("Hostel", 30000); fees.put("Library", 2000);
// for (String item : fees) { } // compile error: a Map is not Iterable
for (String item : fees.keySet()) { System.out.println(item + ": Rs. " + fees.get(item)); }
int total = 0; for (int amount : fees.values()) { total = total + amount; } System.out.println("Total: Rs. " + total); }}Hostel: Rs. 30000 Library: Rs. 2000 Tuition: Rs. 45000 Total: Rs. 77000
What this code does
- A map is not
Iterable, so you loop over one of its views.keySet()gives each key, andget(key)fetches its value. - When you need only the values, loop over
values(). The Maps module addsentrySet(), which gives key and value together.
Mistake 3: the variable's type limits the methods
The compiler checks a call against the declared type. Collection<String> c = new ArrayList<>(); cannot call c.get(0), because Collection has no positions. List<String> names cannot call ensureCapacity, because only ArrayList has it.
Collection<String> c = new ArrayList<>();c.add("Asha");c.get(0); // error: cannot find symbolList<String> names = new ArrayList<>();names.add("Asha");System.out.println(names.get(0)); // fine: List has positionsDeclare with the most general type that still has the methods you need. For a method parameter that only loops, Collection is enough. If you need positions, ask for List. Never write new List<>(): interfaces cannot be created.
The first get(0) fails because a Collection has no positions. The List variable below it has them, so the same call works.
Mistake 4: the wrong family for the job
A list used for uniqueness lets duplicates in, and a list used for lookups makes every search O(n). A HashSet or HashMap printed in a report shows an order that looks random.
Example 3 · Surprise: HashSet has no order
import java.util.HashSet;import java.util.LinkedHashSet;import java.util.Set;
public class SetOrderDemo { public static void main(String[] args) { String[] joined = {"Rohan", "Aarav", "Priya", "Kavya", "Divya"};
Set<String> fast = new HashSet<>(); Set<String> ordered = new LinkedHashSet<>(); for (String name : joined) { fast.add(name); ordered.add(name); } System.out.println("HashSet: " + fast); System.out.println("LinkedHashSet: " + ordered); }}HashSet: [Priya, Aarav, Kavya, Divya, Rohan] LinkedHashSet: [Rohan, Aarav, Priya, Kavya, Divya]
What this code does
- A
HashSetplaces items by their hash code, not by when they were added. The order shown here is what Java 17 prints for these names, but it is not guaranteed: it can change with other data or another Java version. - When the order matters (a joining list, a report), choose
LinkedHashSetfor insertion order orTreeSetfor sorted order.
Example 4 · All four families in one class register
import java.util.ArrayDeque;import java.util.ArrayList;import java.util.List;import java.util.Map;import java.util.Queue;import java.util.Set;import java.util.TreeMap;import java.util.TreeSet;
public class ClassRegisterDemo { public static void main(String[] args) { List<String> joinOrder = new ArrayList<>(); Set<String> subjects = new TreeSet<>(); // unique, sorted Map<String, Integer> marks = new TreeMap<>(); // name -> marks Queue<String> doubts = new ArrayDeque<>(); // first come, first served
joinOrder.add("Priya"); joinOrder.add("Aarav"); joinOrder.add("Rohan");
subjects.add("Physics"); subjects.add("Maths"); subjects.add("Physics");
marks.put("Priya", 88); marks.put("Aarav", 74); marks.put("Rohan", 91);
doubts.offer("Aarav"); doubts.offer("Rohan");
System.out.println("Joined: " + joinOrder); System.out.println("Subjects: " + subjects); System.out.println("Marks: " + marks); System.out.println("Rohan scored " + marks.get("Rohan")); System.out.println("Teacher helps " + doubts.poll() + " first"); System.out.println("Still waiting: " + doubts); }}Joined: [Priya, Aarav, Rohan]
Subjects: [Maths, Physics]
Marks: {Aarav=74, Priya=88, Rohan=91}
Rohan scored 91
Teacher helps Aarav first
Still waiting: [Rohan]What this code does
- Each kind of data gets the family that fits its need: a
Listfor joining order, aSetfor unique subjects, aMapfor lookup by name, aQueuefor doubts in arrival order. - All variables are declared with the interface. The
Treeclasses keep the printed order sorted and stable, so the output is the same on every run.
Ask the four questions again: key lookup → Map, unique → Set, arrival order → Queue, otherwise List. Then pick Hash for speed, LinkedHash for insertion order, Tree for sorted order.
Spot the collections bug
Each snippet below looks almost right. Read what it should do, tap the wrong line, then check the fix.
Find the bug
Find the collections bug
Select the line that is wrong.
Store the price of a product in a list.
Round 1 of 4Finish up
Mark complete & continue
Next: ArrayList: add, get, set, remove