ArrayList and Collections in Java
Store data in lists that grow as needed with ArrayList, sort them with Collections, and look values up by key with HashMap.
Learning objectives
- βCreate an ArrayList and add, get, update and remove elements
- βUse generics such as ArrayList<String> and wrapper types such as Integer
- βLoop over a list with for-each and sort it with Collections.sort
- βStore and look up key-value pairs in a HashMap
π‘ Key points
- ArrayList (in java.util) is a resizable array. It grows and shrinks as you add and remove items.
- Generics in angle brackets fix the element type: ArrayList<String> holds only Strings, and the compiler checks this.
- Collections hold objects only, so write ArrayList<Integer>, not ArrayList<int>. Autoboxing converts between int and Integer for you.
- Key methods are add, get(i), set(i, x), remove, size(), contains, indexOf, isEmpty and clear.
- The Collections class has static helpers: sort, reverse, max, min and shuffle.
- HashMap<K, V> stores key β value pairs with fast lookup by key. Keys are unique, so a put with an existing key replaces the old value.
- A HashMap keeps no particular order. Use LinkedHashMap to keep insertion order, or TreeMap for sorted keys.
π» Code examples(5)
import java.util.ArrayList;
public class ListBasics {
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<>();
names.add("Amit");
names.add("Priya");
names.add("Ravi");
System.out.println(names);
System.out.println(names.size());
names.add(1, "Neha"); // insert at index 1
names.set(0, "Amit K."); // replace index 0
names.remove("Ravi"); // remove by value
System.out.println(names);
System.out.println(names.get(1));
System.out.println(names.contains("Ravi"));
}
}
[Amit, Priya, Ravi] 3 [Amit K., Neha, Priya] Neha false
import java.util.ArrayList;
public class MarksList {
public static void main(String[] args) {
ArrayList<Integer> marks = new ArrayList<>();
marks.add(78);
marks.add(92);
marks.add(65);
marks.add(88);
int total = 0;
for (int m : marks) { // auto-unboxing
total += m;
}
double avg = (double) total / marks.size();
System.out.println("Total: " + total);
System.out.println("Average: " + avg);
}
}
Total: 323 Average: 80.75
import java.util.ArrayList;
import java.util.Collections;
public class SortDemo {
public static void main(String[] args) {
ArrayList<Integer> marks = new ArrayList<>();
Collections.addAll(marks, 78, 92, 65, 88, 71);
Collections.sort(marks);
System.out.println(marks);
Collections.reverse(marks);
System.out.println(marks);
int top = Collections.max(marks);
int low = Collections.min(marks);
System.out.println("Top " + top + ", low " + low);
ArrayList<String> cities = new ArrayList<>();
Collections.addAll(cities, "Pune", "Agra", "Delhi");
Collections.sort(cities);
System.out.println(cities);
}
}
[65, 71, 78, 88, 92] [92, 88, 78, 71, 65] Top 92, low 65 [Agra, Delhi, Pune]
import java.util.HashMap;
public class MapBasics {
public static void main(String[] args) {
HashMap<String, Integer> marks = new HashMap<>();
marks.put("Amit", 78);
marks.put("Priya", 92);
marks.put("Ravi", 65);
marks.put("Amit", 81); // replaces 78
System.out.println(marks.get("Amit"));
System.out.println(marks.get("Neha"));
System.out.println(marks.getOrDefault("Neha", 0));
System.out.println(marks.containsKey("Ravi"));
System.out.println(marks.size());
for (String name : marks.keySet()) {
System.out.println(name + " -> "
+ marks.get(name));
}
}
}
81 null 0 true 3 Priya -> 92 Ravi -> 65 Amit -> 81
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
public class Election {
public static void main(String[] args) {
String[] votes = {"Amit", "Priya", "Amit",
"Ravi", "Priya", "Amit"};
HashMap<String, Integer> count = new HashMap<>();
for (String v : votes) {
count.put(v, count.getOrDefault(v, 0) + 1);
}
ArrayList<String> names =
new ArrayList<>(count.keySet());
Collections.sort(names);
for (String n : names) {
System.out.println(n + ": " + count.get(n));
}
}
}
Amit: 3 Priya: 2 Ravi: 1
π― Practice
Q1. Why can't you write ArrayList<int>?+
Generics work only with objects, not primitives. Use the wrapper class, ArrayList<Integer>. Autoboxing converts between int and Integer automatically.
Q2. list is an ArrayList<Integer> holding [10, 20, 30]. What is it after list.remove(1)?+
[10, 30]. remove(1) with an int removes the element at index 1. To remove the value 20 instead, write list.remove(Integer.valueOf(20)).
Q3. What does map.put("Amit", 90) do if "Amit" is already a key?+
It replaces the old value with 90, because keys are unique. put() also returns the old value, which would be null for a new key.
Q4. Find the highest number in an ArrayList<Integer> called scores.+
int top = Collections.max(scores); // needs import java.util.Collections
Q5. Print every entry of a HashMap<String, Integer> called prices, in the form Pen = Rs.10.+
for (String item : prices.keySet()) { System.out.println(item + " = Rs." + prices.get(item)); }
π Notes
Removing items while looping
Removing from a list inside a for-each loop usually crashes with ConcurrentModificationException. Loop backwards by index instead:
for (int i = names.size() - 1; i >= 0; i--) {
if (names.get(i).startsWith("A")) {
names.remove(i);
}
}
Going backwards means removing an item never shifts the ones you have not checked yet.
The Collections family
- List (
ArrayList,LinkedList) is ordered and allows duplicates. Get items by index. - Set (
HashSet,TreeSet) allows no duplicates. Useful for unique roll numbers. - Map (
HashMap,TreeMap) holds key β value pairs, like a dictionary.
List, Set and Map are interfaces (Day 16), and you will often see the variable declared with the interface type:
List<String> names = new ArrayList<>();
Map<String, Integer> marks = new HashMap<>();
This is upcasting from Day 15, so you can later swap in a different list or map without changing the rest of the code.
Common mistakes
- Using array syntax.
names.lengthandnames[0]don't work on a list. Usenames.size()andnames.get(0). - Mixing up
remove(int)andremove(Object). On anArrayList<Integer>,remove(1)removes by index, not by value. - Unboxing a missing value.
int m = marks.get("Neha");throwsNullPointerExceptionwhen the key is missing. UsegetOrDefault. - Comparing
Integerobjects with==. It happens to work for small values (β128 to 127) but fails for, say, 1000. Useequals(), just like with Strings. - Forgetting the import.
ArrayList,HashMapandCollectionsall live injava.util.
Next: Bring Days 10β20 together in a small project, such as a class register with a Student class, an ArrayList<Student>, exceptions for invalid marks and a HashMap of subject totals.