IndexOutOfBoundsException on List

java.lang.IndexOutOfBoundsException: Index: 3, Size: 2

Quick Answer

You are accessing a List element at an index that is out of range. Check the list size before calling get().

Why This Happens

ArrayList and other List implementations throw IndexOutOfBoundsException when you call get() with an index that is negative or greater than or equal to the list size. Unlike arrays, lists use this parent exception class.

The Problem

List<String> items = List.of("a", "b");
String third = items.get(3); // IndexOutOfBoundsException

The Fix

List<String> items = List.of("a", "b");
if (items.size() > 3) {
    String third = items.get(3);
}

Step-by-Step Fix

  1. 1

    Identify the bad index

    Read the exception to see the requested index and the actual list size.

  2. 2

    Trace the index source

    Find where the index value comes from and why it exceeds the list size.

  3. 3

    Add bounds checking

    Check list.size() before calling get(), or use an iterator or for-each loop instead of index-based access.

Bugsly catches this automatically

Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.

Try Bugsly free