二维ArrayList触发java.lang.IndexOutOfBoundsException错误求助
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

