使用 ArrayList 时出现 IndexoutofboundException

Getting an IndexoutofboundException while using an ArrayList

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

这是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)

您收到的错误是 "IndexOutOfBoundsException" 错误。当您尝试读取或更改数组边界之外的内容时,就会出现这种情况。示例:如果您有一个大小为 4 的数组,并且您尝试读取超出 arrayName[7] 大小的任何元素,则会出现此错误。

在您的情况下,您的代码之所以会出现此错误,是因为您调用了删除 no_duplicate_list.remove(j);。 Remove 是一个重载函数,既可以获取列表中类型的元素,也可以获取索引。看起来您正在尝试使用第一个函数,但因为您将参数作为 int 传递,所以它使用了第二个函数。这告诉代码删除某个位置超出列表边界的元素。

你的问题是你调用 no_duplicate_list.remove(j);j 应该是一个索引而不是一个值。见 official docs.

另一个可能的未来错误是您的代码在以下输入上的逻辑:

1, 2, 1, 2

前两个数字将被添加到列表中,但第三个数字 (1) 已经在列表中,因此它将被删除(如果您解决了将索引传递给 [=14 的问题=] 方法而不是值)。同样适用于第四个数字 2。结果是一个空列表而不是两个值的列表 1, 2.

有两个简单的解决方案:

  1. List 更改为 Set,它的实现会忽略重复项。
  2. 把删除元素的部分代码去掉即可。

我个人的建议是选项 1,如果你不想重复,就不要使用 List 对象,使用 Java 已经为你的问题准备好的东西。

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

如果这是输入数组:

1 2 2 3 3 3 4

输出应如下所示:

1 4

但是您的代码会产生此结果,因为每次出现该数字的时间都不均匀时,它会再次将其添加到 no_duplicate_list:

1 3 4

但这不是您例外的原因。出现异常的原因是因为您将 int j 传递给 List.remove(int position) 并且它试图删除位置 j 的元素,而不是值为 j 的元素。 要解决此问题,您需要先将 int 转换为 Integer,然后再将其从列表中删除,这样您就可以调用 List.remove(Integer object).

no_duplicate_list.remove((Integer)j);

IndexOutOfBounds 的原因已经得到解答。实际问题的逻辑不正确。

以 1,1,1,2,2,3 为例。最初,将 1 添加到 no_dup,然后在接下来将其删除,并在第三次迭代中再次添加 1。最终结果会有1&3,但理想情况下,答案应该是3。

即使输入很大,使用 HashMap 也应该很快。