Module 2 ยท Objects and collections Lesson 6 of 15
ArrayList, HashMap and choosing between them
ArrayList keeps order and gives you item number n in constant time. HashMap keeps key-value pairs and gives you the value for a key in constant time. Reaching for the wrong one is the most common design mistake in junior code.
The concept
ArrayList<String> is an ordered list you can grow: .add, .get(i), .size(), .contains โ the workhorse for rows, names and results. HashMap<String, Integer> maps a key to a value with average O(1) lookup and is how you count, group and de-duplicate.
The collection to reach for is decided by the question. Ordered, index-based access โ a list. Look up a value by its key โ a map. Unique values only, no counting โ a HashSet. Sorted output โ a TreeMap or sort the list at the end. Saying which one and why is a standard fresher interview answer, so decide out loud.
List<String> names = new ArrayList<>(); // ordered, indexed
names.add("Asha");
names.get(0); // O(1)
names.contains("Asha"); // O(n) scan - slow in a loop
Map<String, Integer> counts = new HashMap<>(); // keyed lookup
counts.put("Pune", counts.getOrDefault("Pune", 0) + 1);
counts.get("Pune"); // ~O(1)
// Need insertion order? LinkedHashMap. Sorted keys? TreeMap.Common mistakes
The mistake is contains inside a loop over a large list, which is a hidden O(nยฒ), when a HashSet would make the whole thing one pass. The second is forgetting that a map returns null for a missing key โ use getOrDefault instead of adding one after the fact.
Worked example
A list of students finds "the student with id 1042" by walking every entry; a HashMap<Integer, Student> answers in one step. With 10 rows it does not matter, with 100000 it decides whether the feature ships.
Your practice task
Store the same 200 records in both structures, find one record in each, and write two lines on which you would use in a program that also needs the records sorted.
Do this before moving on. Reading a solution teaches the shape of it; typing it teaches you.
Key takeaway
ArrayList<String> is an ordered list you can grow: .add, .get(i), .size(), .contains โ the workhorse for rows, names and results.
Keep your place in this course
A free account saves which lessons you have finished and unlocks the certificate. The lesson itself stays free to read.
Create free account or sign inCourse complete
You finished every lesson.
Your certificate is ready, and the projects you built are the proof to attach to an application.
Almost there
15 lessons left of 15
Finish every lesson to unlock the certificate. Each one ends in a practice task โ do them and the final project brief writes itself.