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

包实践。实践;

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”抛出了异常。

这是抛出的异常:
阿斯达达夫


  线程“主”中的异常java.lang.IndexOutOfBoundsException:
  索引:7,大小:7 at
  java.util.ArrayList.rangeCheck(ArrayList.java:653)在
  java.util.ArrayList.get(ArrayList.java:429)在
  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)

最佳答案

问题出在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);
}

关于java - 递归调用的IndexOutOfBoundsException,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46947885/

10-09 09:05