Java ArrayList & Collections

Resizable lists and the Collections Framework.

✍️ 2 exercises in this lesson

The Collections Framework provides ready-made data structures. ArrayList is a resizable array:

  • List<String> list = new ArrayList<>();
  • add(), get(i), set(i, v), remove(), size(), contains()
  • Collections.sort(list) or list.sort(...)
  • List.of(...) creates an unmodifiable list.

Collections hold objects, so primitives are wrapped: Integer, Double, Boolean.

Key Takeaways: Java ArrayList & Collections

Mastering Java ArrayList & Collections helps you write clean and reliable Java code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

Java ArrayList & Collections Code Example

Java
import java.util.*;

public class Main {
    public static void main(String[] args) {
        List<String> cities = new ArrayList<>();
        cities.add("Lahore");
        cities.add("Karachi");
        cities.add("Islamabad");
        cities.remove("Karachi");
        cities.add(0, "Peshawar");
        Collections.sort(cities);

        System.out.println(cities);
        System.out.println("Size: " + cities.size());
        System.out.println(cities.contains("Lahore"));

        List<Integer> nums = new ArrayList<>(List.of(5, 3, 9));
        nums.sort(Comparator.reverseOrder());
        System.out.println(nums);
    }
}
Output
[Islamabad, Lahore, Peshawar]
Size: 3
true
[9, 5, 3]
Run this example on your own computer. The "Get Started" lesson shows how to set it up.

Java ArrayList & Collections Practice Exercises

Check what you learned in “Java ArrayList & Collections”.

/ 2 solved
Fill in the blank

Add an item to the list.

cities.("Lahore");
✓ Correct! Not quite. Try again.
Multiple choice

Which interface does ArrayList implement?

✓ Correct! Not quite. Try again.
to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services