Java Arraylist got java.lang.IndexOutOfBoundsException?

被刻印的时光 ゝ 提交于 2019-12-01 05:22:45
Suresh Atta

The following lines:

for (int i = 0; i <= meString.size(); i++) {
    System.out.println(meString.get(i));
}

should be:

for (int i = 0; i < meString.size(); i++) {
    System.out.println(meString.get(i));
}

This is because the index of the list starts from zero.

Index: 4, Size: 4 explains a little more. When you call get(4), an exception occurs because your list only has a size of 4. get(4) would attempt to access the 5th element in the list.

Valid elements you can access would be get(0), get(1), get(2), get(3).

You asked, "Why does Arraylist, which can stretch its capacity by its own still get an OutOfBoundsException ???"
The answer is: an ArrayList only stretches its capacity when:

  1. You add an object to it ( .add(Object o) ).
  2. You add the contents of another collection to it ( .addAll(Collection c) ).
  3. You ensure its size ( .ensureCapacity(int minCapacity) ).

The trouble you're having is that you are trying to access an object in an index of the list that doesn't exist. While an ArrayList will dynamically resize when you change the contents, it won't do it when you are simply trying to access the contents.
That is the difference.
To avoid accessing an index that doesn't exist:

  1. Take Surresh Atta's suggestion: Use i < meString.size() instead of i <= meString.size() because the index starts with 0 instead of 1.
  2. Take Ankit's suggestion and just use the enhanced for loop: for(String str : meString).
Ankit

Use the above answer, or you can use a foreach loop:

for (String str: meString) {
    System.out.println(str);
}

If you are using a 2D ArrayList ,make sure you instantiate every row and every element of the corresponding row using the following code:

 for(int i=0;i<n;i++)
    {
        p.add(new ArrayList<Integer>());
        for(int j=0;j<n;j++)
        {
            p.get(i).add(new Integer(0));
        }
    }

This creates an ArrayList with i (=n) rows and each row contains an ArrayList with j (=n) number of elements.

If instantiation is not done properly it might result in an IndexOutOfBoundsException

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!