简体   繁体   English

ArrayList索引超出范围异常

[英]ArrayList index out of bounds exception

Recently while using arrayList I found a weird issue. 最近在使用arrayList时,我发现了一个奇怪的问题。 I want to keep 2 elements in the arraylist and would like to keep object1 in element 0 and object2 in element1. 我想将2个元素保留在arraylist中,并希望将object1保留在element 0中,将object2保留在element1中。

I am deciding this in a loop. 我正在循环决定这一点。

When it happens to add the first element its throwing indexOutofBounds. 当碰巧添加第一个元素时,将其抛出indexOutofBounds。 As per java doc as the index is greater than size its doing this. 根据java doc,索引大于其大小。

public static void main(String[] args) 
    {
        ArrayList<String> list = new ArrayList<String>();
        list.add(1,"SECONDITEM"); // throwing  due to size is not set
        list.add(0,"FIRSTITEM");

        int postn=0;
        for(String item:list){

            System.out.println("Position "+postn+" :"+item);
            postn++;
        }
    }

Then I tried to setup other items as placeholder in 0,1 element and tried to do same 然后我尝试将其他项目设置为0,1元素中的占位符,并尝试执行相同的操作

    public static void main(String[] args) 
    {
        ArrayList<String> list = new ArrayList<String>();
        list.add(0,"x");
        list.add(1,"y");

        list.add(1,"SECONDITEM");

        list.add(0,"FIRSTITEM");

        int postn=0;
        for(String item:list){

            System.out.println("Position "+postn+" :"+item);
            postn++;
        }
    }

    Output:
    Position 0 :FIRSTITEM
    Position 1 :x
    Position 2 :SECONDITEM
    Position 3 :y

How to get over this issue. 如何解决这个问题。 One way I found is to remove the element in the index and add the element. 我发现的一种方法是删除索引中的元素并添加该元素。 Is there a better option. 有没有更好的选择。

public static void main(String[] args) 
    {
        ArrayList<String> list = new ArrayList<String>();
        list.add(0,"x");
        list.add(1,"y");
        list.remove(1);
        list.add(1,"SECONDITEM");
        list.remove(0);
        list.add(0,"FIRSTITEM");

        int postn=0;
        for(String item:list){

            System.out.println("Position "+postn+" :"+item);
            postn++;
        }
    }

    Position 0 :FIRSTITEM
    Position 1 :SECONDITEM

.add() method insert the element at the given position and shift the other element accordingly .add()方法将元素插入到给定位置,并相应地移动另一个元素

to overwrite the value at particular index you have to use the .set(position, value) 要覆盖特定索引的值,您必须使用.set(position,value)

try the set method .. 尝试设置方法..

    list.add(0,"x");
    list.add(1,"y");

    list.set(1,"SECONDITEM");

    list.set(0,"FIRSTITEM");

now it will return the only two values. 现在它将仅返回两个值。

The issue is ... you're trying to use a List in a way it wasn't intended to be used. 问题是...您正试图以一种不希望使用的方式来使用List As you've found out, you can't set or add to an index that is outside the range of the current size. 如您所知,您无法设置或添加超出当前大小范围的索引。

If you know in advance the size you need and it's a fixed size, using a String[] is the better choice. 如果您事先知道所需的大小,并且它是固定大小,则使用String[]是更好的选择。

If you really want/need a dynamic structure that allows random access sets regardless of the current size, write your own method to fill the list when needed: 如果您确实希望/需要一种动态结构,无论当前大小如何,都允许随机访问集,请在需要时编写自己的方法来填充列表:

public static <T> void fillAndSet(int index, T object, List<T> list) 
{
    if (index > (list.size() - 1))
    {
        for (int i = list.size(); i < index; i++)
        {
            list.add(null);
        }
        list.add(object);
    }
    else
    {
        list.set(index, object);
    }
 }


When you call in this order: 当您按此顺序致电时:

ArrayList<String> list = new ArrayList<String>();
list.add(1,"SECONDITEM"); // throwing  due to size is not set

You are trying to add to position "1", but nothing has been added to the list yet. 您正在尝试添加到位置“ 1”,但尚未将任何内容添加到列表中。 I believe that is why you get the error. 我相信这就是您得到错误的原因。 Instead you probably want to use just: 相反,您可能只想使用:

ArrayList<String> list = new ArrayList<String>();
list.add("FIRSTITEM");

Since it's an empty list. 由于它是一个空列表。 You can also use the index, but you'll have to increment each time. 您也可以使用索引,但是每次都必须增加。 Makes sense? 说得通?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM