Java Basics, Java Programming · December 2, 2026

Java for Beginners, Lesson 27: ArrayList and Wrapper Classes in Java

Java for Beginners · Module 5: Data and Methods


🎯 When an Array Is Not Flexible Enough

An array has a fixed size. If you do not know how many marks, names or messages you will receive, you have to guess a size in advance. ArrayList solves this: it is a resizable list that grows as you add elements and shrinks as you remove them. It lives in java.util.

📌 An ArrayList is a resizable array of objects. Because it holds objects, primitive values are stored through wrapper classes: int becomes Integer, double becomes Double, and so on.
ArrayArrayList
Sizefixed when createdgrows and shrinks automatically
Holdsprimitives or objectsobjects only (wrapper types such as Integer)
Lengtha.lengthlist.size()
Read / writea[i]list.get(i) / list.set(i, x)
Add / removenot possibleadd, remove, clear
Import needednoimport java.util.ArrayList;

Figure 1: Array versus ArrayList.

1️⃣ Using an ArrayList

The type in angle brackets <String> says what the list holds. It is called a generic type, and it makes Java check that you add only Strings.

MethodWhat it does
add(x)adds at the end
add(i, x)inserts at position i
get(i)reads element i
set(i, x)replaces element i
remove(i) / remove(obj)removes by position / by value
size()number of elements
contains(x), indexOf(x)search
isEmpty(), clear()test / empty the list

Figure 2: The ArrayList methods you will use most.

Program 1: Add, read, change and remove

import java.util.ArrayList;

public class ListBasics {
    public static void main(String[] args) {
        ArrayList<String> names = new ArrayList<>();
        names.add("Ajay");
        names.add("Rahul");
        names.add("Priya");
        System.out.println(names);
        System.out.println("size = " + names.size());
        System.out.println("get(1) = " + names.get(1));

        names.add(1, "Sana");
        System.out.println("after add(1, Sana): " + names);
        names.set(0, "Ajay D");
        names.remove("Rahul");
        names.remove(0);
        System.out.println("after set/remove: " + names);
        System.out.println("contains Priya? " + names.contains("Priya"));
        System.out.println("indexOf Priya = " + names.indexOf("Priya"));
        System.out.println("isEmpty? " + names.isEmpty());

        for (String n : names) {
            System.out.println("Hello " + n);
        }
        names.clear();
        System.out.println("after clear: " + names + ", size = " + names.size());
    }
}
🖥️ Output:
[Ajay, Rahul, Priya]
size = 3
get(1) = Rahul
after add(1, Sana): [Ajay, Sana, Rahul, Priya]
after set/remove: [Sana, Priya]
contains Priya? true
indexOf Priya = 1
isEmpty? false
Hello Sana
Hello Priya
after clear: [], size = 0
  • Printing a list shows its contents in square brackets. No Arrays.toString is needed.
  • add(1, "Sana") inserts at position 1 and shifts the later elements right.
  • After set(0, "Ajay D"), remove("Rahul") and remove(0) (which removes “Ajay D” at position 0), the list is [Sana, Priya].
  • The for-each loop (Lesson 19) works on lists exactly as it does on arrays.
  • The empty angle brackets in new ArrayList<>() mean “work out the type from the left side”.

2️⃣ Wrapper Classes

PrimitiveWrapper class
byteByte
shortShort
intInteger
longLong
floatFloat
doubleDouble
charCharacter
booleanBoolean

Figure 3: Every primitive has a wrapper class.

int 5
autoboxing ➜
Integer object
stored in the list
unboxing ➜
int 5
Java converts between a primitive and its wrapper automatically, so list.add(5) and int x = list.get(0) just work.

Figure 4: Autoboxing and unboxing.

A list cannot hold int, only Integer. Java converts automatically, so you rarely notice. Wrapper classes also carry useful tools such as limits and parsing methods.

import java.util.ArrayList;
import java.util.Collections;

public class Wrappers {
    public static void main(String[] args) {
        ArrayList<Integer> marks = new ArrayList<>();
        marks.add(70);
        marks.add(95);
        marks.add(82);
        marks.add(61);

        int total = 0;
        for (int m : marks) {
            total += m;
        }
        System.out.println("marks = " + marks + ", total = " + total);
        System.out.println("max = " + Collections.max(marks) + ", min = " + Collections.min(marks));
        Collections.sort(marks);
        System.out.println("sorted = " + marks);
        Collections.reverse(marks);
        System.out.println("reversed = " + marks);

        Integer boxed = 100;
        int plain = boxed;
        System.out.println("boxed = " + boxed + ", plain = " + plain);

        System.out.println("Integer.MAX_VALUE = " + Integer.MAX_VALUE);
        System.out.println("Integer.parseInt(\"42\") + 1 = " + (Integer.parseInt("42") + 1));
        System.out.println("Integer.toBinaryString(10) = " + Integer.toBinaryString(10));
        System.out.println("Double.parseDouble(\"2.5\") = " + Double.parseDouble("2.5"));
        System.out.println("Character.isDigit('7') = " + Character.isDigit('7'));
    }
}
🖥️ Output:
marks = [70, 95, 82, 61], total = 308
max = 95, min = 61
sorted = [61, 70, 82, 95]
reversed = [95, 82, 70, 61]
boxed = 100, plain = 100
Integer.MAX_VALUE = 2147483647
Integer.parseInt(“42”) + 1 = 43
Integer.toBinaryString(10) = 1010
Double.parseDouble(“2.5”) = 2.5
Character.isDigit(‘7’) = true
  • marks.add(70) boxes the int into an Integer. for (int m : marks) unboxes each one.
  • Collections (note the s) is a helper class with sort, reverse, max, min and more.
  • You have already used wrapper tools: Integer.parseInt (Lesson 9), Integer.MAX_VALUE (Lesson 8) and Character.isDigit (Lesson 8).

3️⃣ Two Traps with Integer

import java.util.ArrayList;

public class RemoveTrap {
    public static void main(String[] args) {
        ArrayList<Integer> list = new ArrayList<>();
        list.add(10);
        list.add(20);
        list.add(30);
        list.add(1);

        list.remove(1);
        System.out.println("remove(1)                    -> " + list);

        list.remove(Integer.valueOf(1));
        System.out.println("remove(Integer.valueOf(1))   -> " + list);

        Integer a = 127, b = 127;
        Integer c = 1000, d = 1000;
        System.out.println("127 == 127   : " + (a == b));
        System.out.println("1000 == 1000 : " + (c == d));
        System.out.println("1000 equals  : " + c.equals(d));
    }
}
🖥️ Output:
remove(1) -> [10, 30, 1]
remove(Integer.valueOf(1)) -> [10, 30]
127 == 127 : true
1000 == 1000 : false
1000 equals : true
  • remove(int) versus remove(Object): on a list of Integers, remove(1) removes the element at index 1 (the 20), not the value 1. To remove the value, write remove(Integer.valueOf(1)).
  • == on wrappers: Java caches small Integer objects (-128 to 127), so 127 == 127 happens to be true. For 1000 two separate objects are created and == is false. This is the same lesson as Strings (Lesson 23): compare objects with equals().

4️⃣ Filtering and Converting

The next program uses removeIf with a short form n -> n % 3 == 0 (a lambda). Read it as “remove every n for which n % 3 == 0 is true”. Lambdas are an advanced topic you will meet later.

import java.util.ArrayList;

public class Filter {
    public static void main(String[] args) {
        ArrayList<Integer> nums = new ArrayList<>();
        for (int i = 1; i <= 10; i++) nums.add(i);

        ArrayList<Integer> evens = new ArrayList<>();
        for (int n : nums) {
            if (n % 2 == 0) evens.add(n);
        }
        System.out.println("evens = " + evens);

        nums.removeIf(n -> n % 3 == 0);
        System.out.println("without multiples of 3 = " + nums);

        int[] arr = {5, 3, 8};
        ArrayList<Integer> fromArray = new ArrayList<>();
        for (int x : arr) fromArray.add(x);
        Integer[] back = fromArray.toArray(new Integer[0]);
        System.out.println("list = " + fromArray + ", array length = " + back.length);
    }
}
🖥️ Output:
evens = [2, 4, 6, 8, 10]
without multiples of 3 = [1, 2, 4, 5, 7, 8, 10]
list = [5, 3, 8], array length = 3
  • To filter, loop and add the wanted items to a new list.
  • Removing items while looping over the same list with for-each is not allowed (it fails at run time). removeIf does it safely.
  • To move between an array and a list, copy with a loop, or use toArray.

5️⃣ Errors Beginners Meet

Primitive type inside the brackets

import java.util.ArrayList;

public class Bad1 {
    public static void main(String[] args) {
        ArrayList<int> list = new ArrayList<>();
    }
}
🖥️ Compiler message:
Bad1.java:5: error: unexpected type
ArrayList<int> list = new ArrayList<>();
^
required: reference
found: int
1 error
  • Use the wrapper: ArrayList<Integer>.

Forgetting the import

public class Bad2 {
    public static void main(String[] args) {
        ArrayList<String> names = new ArrayList<>();
        names.add("Ajay");
    }
}
🖥️ Compiler message:
Bad2.java:3: error: cannot find symbol
ArrayList<String> names = new ArrayList<>();
^
symbol: class ArrayList
location: class Bad2
Bad2.java:3: error: cannot find symbol
ArrayList<String> names = new ArrayList<>();
^
symbol: class ArrayList
location: class Bad2
2 errors
  • Add import java.util.ArrayList; at the top (Lesson 10).

Mixing up array and list syntax

import java.util.ArrayList;

public class Bad3 {
    public static void main(String[] args) {
        ArrayList<String> names = new ArrayList<>();
        names.add(5);
        names.add("Ajay");
        System.out.println(names.length());
        System.out.println(names[0]);
        System.out.println(names.get(3));
    }
}
🖥️ Compiler message:
Bad3.java:6: error: incompatible types: int cannot be converted to String
names.add(5);
^
Bad3.java:8: error: cannot find symbol
System.out.println(names.length());
^
symbol: method length()
location: variable names of type ArrayList<String>
Bad3.java:9: error: array required, but ArrayList<String> found
System.out.println(names[0]);
^
3 errors
  • A String list accepts only Strings. Use size() instead of length, and get(0) instead of [0].

An index that does not exist (runtime)

import java.util.ArrayList;

public class Idx {
    public static void main(String[] args) {
        ArrayList<String> names = new ArrayList<>();
        names.add("Ajay");
        System.out.println(names.get(3));
    }
}
🖥️ Runtime error (trimmed):
Exception in thread “main” java.lang.IndexOutOfBoundsException: Index 3 out of bounds for length 1
at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:100)
… (internal lines)

⚠️ Common Mistakes

MistakeProblemFix
ArrayList<int>Primitives not allowedArrayList<Integer>
list.length or list[0]That is array syntaxlist.size(), list.get(0)
list.remove(1) on IntegersRemoves index 1, not the valueremove(Integer.valueOf(1))
Comparing Integers with ==Works only for small cached valuesUse equals()
Removing inside a for-each loopConcurrentModificationExceptionUse removeIf or an index loop
Forgetting the importcannot find symbolimport java.util.ArrayList;

❓ Frequently Asked Questions

Q1. Is ArrayList slower than an array?
Slightly, because of boxing and resizing. For most programs the difference does not matter.

Q2. How does it grow?
Internally it holds an array and creates a bigger one when full, copying the elements across. You never see this.

Q3. Can an ArrayList hold different types?
Only if declared as ArrayList<Object>, which is rarely a good idea. Normally a list holds one type.

Q4. What are the other collections?
LinkedList, HashSet, HashMap and more. They are part of the Java Collections Framework, a natural next topic after this series.

✅ Key Takeaways

  • ArrayList is a resizable list from java.util: add, get, set, remove, size, contains.
  • It holds objects, so use wrappers: ArrayList<Integer>, not ArrayList<int>.
  • Autoboxing and unboxing convert between int and Integer automatically.
  • remove(int index) and remove(Object) are different: on an Integer list use Integer.valueOf to remove a value.
  • Compare wrapper objects with equals(), not ==.
  • Collections.sort, max, min and reverse are ready-made helpers.
🎓 Practice questions: (1) Read numbers from the user until 0 and store them in an ArrayList; print the sum and average. (2) Remove all duplicate values from a list. (3) Explain why list.remove(1) on an ArrayList<Integer> may not do what you expect. (4) Sort a list of names alphabetically. (5) Write a method that takes an ArrayList<Integer> and returns a new list of only its even numbers.
All 30 lessons in this series (open course page)

Module 1 · Getting Started

Module 2 · Building Blocks

Module 3 · Operators

Module 4 · Control Flow

Module 5 · Data and Methods

Module 6 · Objects and Revision