简体   繁体   English

ArrayList Java中的IndexOutOfBoundsException

[英]IndexOutOfBoundsException in ArrayList Java

Whenever I try to run the code I get IndexOutOfBoundsException. 每当我尝试运行代码时,我都会得到IndexOutOfBoundsException。 I have tried numerous of ways fixing it but none of them have helped. 我尝试了许多修复它的方法,但是都没有帮助。 The method should add a new String element "****" into ArrayList before every String which's length is equal to 4. In this case, it must add "****" before "5555". 该方法应在每个长度等于4的String之前,在ArrayList中添加一个新的String元素“ ****”。在这种情况下,必须在“ 5555”之前添加“ ****”。

Where could be the problem? 问题可能出在哪里?

import java.util.ArrayList;

public class Main {

    public static ArrayList<String> markLength4(ArrayList<String> list) {

        int sum = 0;
        for ( int i = 0; i < list.size(); i++) {
            if (list.get(i).length() == 4) {
                list.add(list.indexOf(i), "****");
            }
        } 
        return  list;
    }

    public static void main(String[] args) {

        ArrayList<String> list = new ArrayList<>();
        list.add("ddddddddddddd");
        list.add("fffffffffffff");
        list.add("5555fdgdfg");
        list.add("5555");
        list.add("5555");

        System.out.println(markLength4(list));
    }
}

list.indexOf(i) will return -1 , since i doesn't appear in your list. list.indexOf(i)将返回-1 ,因为i没有出现在您的列表中。 Therefore adding an element at the -1 position will throw an exception. 因此,在-1位置添加元素将引发异常。

If you change list.add(list.indexOf(i), "****") to list.add(i, "****"); 如果将list.add(list.indexOf(i), "****")更改为list.add(i, "****"); , you'll get an infinite loop that will end with OutOfMemoryError , since the newly added String also has a length() of 4, so another String will be added on the next iteration, and so on. ,您将获得一个以OutOfMemoryError结尾的无限循环,因为新添加的Stringlength()为4,因此在下一次迭代时将添加另一个String ,依此类推。

i is not in your arraylist - it is a list of String , not Integer . i不在您的arraylist中-它是String而不是Integer的列表。 That means that list.indexOf(i) == -1 . 那意味着list.indexOf(i) == -1

From your description, I think you mean: 根据您的描述,我认为您的意思是:

list.add(i, "****");

but you will also need to increment i , eg 但是您还需要增加i ,例如

list.add(i++, "****");

to avoid the infinite loop that Eran mentions. 避免Eran提到的无限循环。

Or, of course, you can iterate the list backwards, and avoid the infinite loop/need to change the loop variable inside the loop body: 或者,当然,您可以向后迭代列表,避免无限循环/需要在循环体内更改循环变量:

for ( int i = list.size() - 1; i >= 0; i--)
{
  if (list.get(i).length() == 4)
  {
    list.add(i, "****");
  }
}
import java.util.ArrayList;

public class Test {

    public static ArrayList<String> markLength4(ArrayList<String> list) {
        int sum = 0;
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).length() == 4) {
                list.add(i++, "****");
            }
        }
        return list;
    }

    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        list.add("ddddddddddddd");
        list.add("fffffffffffff");
        list.add("5555fdgdfg");
        list.add("5555");
        list.add("5555");
        list = markLength4(list);
        for (String x : list) {
            System.out.println(x);
        }
    }
}

You'll loop forever this way, because there's 4-lengthened strings forward and you keep adding... 您将永远这样循环,因为向前有4个加长的字符串,并且您会不断添加...
You can solve this by looping from the end, but you'll have to be careful with your index(you should add and increment the index to avoid that) 您可以通过从头开始循环来解决此问题,但是您必须小心使用索引(应增加和增加索引以避免这种情况)

After Editing list.add(i++,"****"); 编辑后list.add(i++,"****"); the code should work just fine. 该代码应该可以正常工作。

Notable 显着
If you want to add before use i++; 如果要在使用i++;之前添加i++; .
If you want to add after your match use ++i; 如果您想在比赛后添加,请使用++i; .

list.indexOf(i) where i is an int and therefore not in your list will throw your error as stated in comments (index -1). list.indexOf(i)其中i是一个int值,因此不在列表中,它将引发注释(索引-1)中所述的错误。

use either of the following: 使用以下任一方法:

list.add("str") to add a String to the end of the list list.add("str")将字符串添加到列表的末尾

OR 要么

list.set(i, "****") which will set the value at a given index to this new string. list.set(i, "****")会将给定索引的值设置为此新字符串。

list.indexOf(i) is not present in the list . list.indexOf(i)不存在于list中。 It will produce -1 它将产生-1

-1 is not available in ArrayList -1在ArrayList中不可用

Replace the Line list.add(list.indexOf(i), "****"); 替换行list.add(list.indexOf(i),“ ****”);

with the following line 与以下行

list.set(i, "****"); list.set(i,“ ****”);

It replace the existing content of the List with new element in the index of i with new element ie (****) 它用新元素(即(****))将i的索引中的新元素替换为List的现有内容。

In the markLength4 method, by adding the element in the for loop you keep adding Strings and increasing the list size. 在markLength4方法中,通过在for循环中添加元素,可以继续添加Strings并增加列表大小。 You need a flag that tells the index and then ends the loop. 您需要一个标志来告诉索引,然后结束循环。 You can try something like that 你可以尝试这样的事情

public static ArrayList<String> markLength4(ArrayList<String> list) {

    int i = 0;
    boolean found = false;
    int pos = 0;

    while(i < list.size() && !found){
        if (list.get(i).length() == 4) {
            found = true;
            pos = i;
        }
        i++;
    }
    list.add(pos, "****");
    return list;
}

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

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