首页 > 解决方案 > 使用 ArrayList 时获取 IndexoutofboundException

问题描述

给定一个数字列表,使得除了一个元素之外的所有元素在列表中出现不止一次。找出只出现一次的元素。

这是Java实现:

package competitiveprograming;
import java.util.*;

public class FindSingleInArray {

    public static void main(String[] args) {
        Scanner sc= new Scanner(System.in);
        System.out.print("Enter size of array");
        int size=sc.nextInt();
        System.out.print("Enter an element where one of the element will not repeat again..");
        int arr[]= new int[10];
        for(int i=0;i<size;i++)
        {
            arr[i]=sc.nextInt();
        }

        List<Integer> no_duplicate_list= new ArrayList<Integer>();

        for(int j : arr)
        {
            if(!no_duplicate_list.contains(j))
            {
                no_duplicate_list.add(j);
            }
            else
            {
                no_duplicate_list.remove(j);
            }
        }

        System.out.print(no_duplicate_list.get(0));
        sc.close();
    }
}

这是我收到的错误消息:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 2 out of bounds for length 1
    at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
    at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)
    at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:248)
    at java.base/java.util.Objects.checkIndex(Objects.java:373)
    at java.base/java.util.ArrayList.remove(ArrayList.java:502)
    at competitiveprograming/competitiveprograming.FindSingleInArray.main(FindSingleInArray.java:28)

标签: javaarraylistindexoutofboundsexception

解决方案


如果我理解正确,您正在尝试查找输入数组中未重复的所有元素。

因此,如果这是输入数组:

1 2 2 3 3 3 4

输出应如下所示:

1 4

但是你的代码会产生这个,因为每次出现不均匀的数字时,它都会再次将它添加到 no_duplicate_list 中:

1 3 4

但是,这不是您例外的原因。异常的原因是因为您传递了一个int jtoList.remove(int position)并且它试图删除 position 处的元素j,而不是值为 的元素j。要解决此问题,您需要在将其从列表中删除之前进行int转换Integer,这样您就可以调用List.remove(Integer object).

no_duplicate_list.remove((Integer)j);

推荐阅读