You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

二维ArrayList触发java.lang.IndexOutOfBoundsException错误求助

Java IndexOutOfBoundsException with Nested ArrayLists

Hey there, let's break down why you're hitting this error and fix it up quickly.

First, here's your code as provided:

import java.util.ArrayList;
public class Main {
    public static void main(String[] args) {
        ArrayList<ArrayList<Integer>> arrayLists = new ArrayList<ArrayList<Integer>>();
        arrayLists.get(0).add(100);
        arrayLists.get(0).add(50);
        arrayLists.get(1).add(67);
        System.out.println(arrayLists.get(0).get(0));
    }
}

And the error you encountered:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 at java.util.ArrayList.rangeCheck(ArrayList....

What's Causing This?

The core issue is simple: you initialized the outer ArrayList, but it starts completely empty—there are no inner ArrayList<Integer> objects inside it yet. When you call arrayLists.get(0), you're trying to access the element at index 0, but the outer list has a size of 0. That's exactly why the IndexOutOfBoundsException gets thrown.

How to Fix It

You need to first add empty inner ArrayList instances to the outer list before you can access and modify them. Here's the corrected working code:

import java.util.ArrayList;
public class Main {
    public static void main(String[] args) {
        ArrayList<ArrayList<Integer>> arrayLists = new ArrayList<ArrayList<Integer>>();
        
        // Add the first inner ArrayList to the outer list first
        arrayLists.add(new ArrayList<>());
        arrayLists.get(0).add(100);
        arrayLists.get(0).add(50);
        
        // Do the same for the second inner ArrayList
        arrayLists.add(new ArrayList<>());
        arrayLists.get(1).add(67);
        
        System.out.println(arrayLists.get(0).get(0)); // This will now print 100
    }
}

Bonus: Dynamic Inner List Creation

If you're working with a variable number of inner lists (and don't want to manually add() each one upfront), you can add a check to create the inner list on the fly when you need it:

int targetIndex = 0;
// Check if the target index is beyond the current size, or if the element is null
if (targetIndex >= arrayLists.size() || arrayLists.get(targetIndex) == null) {
    arrayLists.add(new ArrayList<>());
}
// Now safely add elements to the inner list
arrayLists.get(targetIndex).add(100);

This way, you won't have to pre-add all inner lists manually—they'll be created as you need them.

内容的提问来源于stack exchange,提问作者Mert Yanık

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:55:48