ArrayList

A plain array has a fixed size — once it's 5 elements long, it's always 5. Real programs rarely know the size in advance. ArrayList is a resizable list that grows and shrinks on demand, with friendly methods to add, find, and remove items.

Learn ArrayList in our free Java course — a beginner-friendly interactive lesson with worked examples, a practice exercise and a quick reference.

Part of the free Java course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

An array is a fixed-size row of boxes. An ArrayList is a row of boxes that can add or remove boxes whenever you like.

You need to import it: import java.util.ArrayList; . The part in angle brackets — the generic type — declares what the list holds, e.g. for text or for whole numbers.

The java.util.Collections class provides static helpers that operate on any list:

Note the easy mix-up: Collections (helper methods) is a different class from Collection (the interface all collections implement).

Reorder these lines to create a list of two colors and print its size.

Why: The list must be created before anything can be added to it, and both add calls must run before size() reports the count. Output: 2 .

[y, x] . add(0, "y") inserts "y" at index 0, pushing "x" to index 1.

[10, 30] . remove(1) deletes the element at index 1 (the value 20), not the value 1.

3. What does indexOf return for a value that isn't present?

-1 . That's the universal "not found" sentinel; check contains first if you only need a yes/no.

You can now use Java's workhorse collection: create a generic ArrayList , add/get/set/remove elements, query it with size / contains / indexOf , loop with for-each, and sort or reverse with Collections . You also know the remove(index) vs remove(value) trap.

Next up: HashMap — store key→value pairs for instant lookups, like a phone book or a word-count tally.

Practice quiz

What is the key advantage of an ArrayList over a plain array?

  • It is always faster
  • It can hold primitives directly
  • It grows and shrinks automatically
  • It needs no import

Answer: It grows and shrinks automatically. An ArrayList resizes automatically, unlike a fixed-size array.

Which is the correct way to declare a list of whole numbers?

  • ArrayList<Integer>
  • ArrayList<int>
  • ArrayList<number>

Answer: ArrayList<Integer>. Lists hold objects, so use the wrapper Integer, not the primitive int.

Given a list [10, 20, 30], what does remove(1) do?

  • Removes the value 1
  • Removes the first element
  • Throws an error
  • Removes the element at index 1 (the 20)

Answer: Removes the element at index 1 (the 20). remove(int) removes by index, so remove(1) deletes index 1 (the value 20), leaving [10, 30].