递归调用的IndexOutOfBoundsException

时间:2017-10-26 07:10:21

标签: java recursion

这是我的代码,应该删除连续的重复项。

包Practice.Practice;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

public class RemoveConsecutiveDuplicates {
    private static int i=1;
    public static List<String> detectDuplicates(List<String> chars) {
        if(i>chars.size())
            return chars;
        while(chars.get(i-1).equals(chars.get(i))) {
            chars.remove(i);
        }
        i++;
        return detectDuplicates(chars);


    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String str = scanner.nextLine();
        List<String> chars = new ArrayList<String>(Arrays.asList(str.split("")));
        System.out.println(detectDuplicates(chars));

    }
}

它为输入“asssddaaffgff”抛出了异常。

这是抛出的异常: 的 asssddaaffgff

  

线程“main”中的异常 java.lang.IndexOutOfBoundsException:   指数:7,大小:7点   java.util.ArrayList.rangeCheck(ArrayList.java:653)at   java.util.ArrayList.get(ArrayList.java:429)at   Practice.Practice.RemoveConsecutiveDuplicates.detectDuplicates(RemoveConsecutiveDuplicates.java:13)     在   Practice.Practice.RemoveConsecutiveDuplicates.detectDuplicates(RemoveConsecutiveDuplicates.java:17)     在   Practice.Practice.RemoveConsecutiveDuplicates.detectDuplicates(RemoveConsecutiveDuplicates.java:17)     在   Practice.Practice.RemoveConsecutiveDuplicates.detectDuplicates(RemoveConsecutiveDuplicates.java:17)     在   Practice.Practice.RemoveConsecutiveDuplicates.detectDuplicates(RemoveConsecutiveDuplicates.java:17)     在   Practice.Practice.RemoveConsecutiveDuplicates.detectDuplicates(RemoveConsecutiveDuplicates.java:17)     在   Practice.Practice.RemoveConsecutiveDuplicates.detectDuplicates(RemoveConsecutiveDuplicates.java:17)     在   Practice.Practice.RemoveConsecutiveDuplicates.main(RemoveConsecutiveDuplicates.java:26)

2 个答案:

答案 0 :(得分:2)

您需要在while循环中进行检查,因为chars.size()在删除时会发生变化。你可以在自己的时候做到这一点。

...
while((i<chars.size()) && (chars.get(i-1).equals(chars.get(i)))) {
    chars.remove(i);
}
i++;
return detectDuplicates(chars);
...

答案 1 :(得分:1)

问题出在while循环:

while(chars.get(i-1).equals(chars.get(i)))

在这里删除元素。因此,List的大小以及chars.size()方法返回的值会发生变化。

更改while循环如下:

public static List<String> detectDuplicates(List<String> chars) {
    while(i<chars.size() && chars.get(i-1).equals(chars.get(i))) {
        chars.remove(i);
    }
    i++;

    if(i>chars.size())  return chars;
    return detectDuplicates(chars);
}