Board Formulas
β˜• JavaπŸ“… Day 20

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)

#1ArrayList basics
java
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"));
    }
}
Output
[Amit, Priya, Ravi]
3
[Amit K., Neha, Priya]
Neha
false
The empty <> (the diamond) lets Java take the type String from the left side. Unlike an array, the list makes room when you insert and closes the gap when you remove. Printing a list shows every element in square brackets.
#2A list of marks with for-each
java
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);
    }
}
Output
Total: 323
Average: 80.75
The list holds Integer objects, and for-each unboxes each one into an int. Use size() to get the count, because an ArrayList has no length field.
#3Collections.sort, reverse, max and min
java
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);
    }
}
Output
[65, 71, 78, 88, 92]
[92, 88, 78, 71, 65]
Top 92, low 65
[Agra, Delhi, Pune]
Collections is a helper class full of static methods. sort() puts numbers in ascending order and Strings in dictionary order, using compareTo() from Day 11. Calling reverse() after sort() gives descending order.
#4HashMap basics
java
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));
        }
    }
}
Output
81
null
0
true
3
Priya -> 92
Ravi -> 65
Amit -> 81
get() returns null for a missing key, and getOrDefault() lets you choose a fallback. The loop visits keys in the map's own internal order, not the order you added them, so never rely on HashMap order.
#5Counting votes for class monitor
java
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));
        }
    }
}
Output
Amit: 3
Priya: 2
Ravi: 1
getOrDefault(v, 0) returns 0 the first time a name appears, so one line handles both new and repeated names. Copying the keys into an ArrayList and sorting it gives a predictable alphabetical order.

🎯 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.length and names[0] don't work on a list. Use names.size() and names.get(0).
  • Mixing up remove(int) and remove(Object). On an ArrayList<Integer>, remove(1) removes by index, not by value.
  • Unboxing a missing value. int m = marks.get("Neha"); throws NullPointerException when the key is missing. Use getOrDefault.
  • Comparing Integer objects with ==. It happens to work for small values (βˆ’128 to 127) but fails for, say, 1000. Use equals(), just like with Strings.
  • Forgetting the import. ArrayList, HashMap and Collections all live in java.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.