java - 使用 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)
解决方案
如果我理解正确,您正在尝试查找输入数组中未重复的所有元素。
因此,如果这是输入数组:
1 2 2 3 3 3 4
输出应如下所示:
1 4
但是你的代码会产生这个,因为每次出现不均匀的数字时,它都会再次将它添加到 no_duplicate_list 中:
1 3 4
但是,这不是您例外的原因。异常的原因是因为您传递了一个int j
toList.remove(int position)
并且它试图删除 position 处的元素j
,而不是值为 的元素j
。要解决此问题,您需要在将其从列表中删除之前进行int
转换Integer
,这样您就可以调用List.remove(Integer object)
.
no_duplicate_list.remove((Integer)j);
推荐阅读
- blender - Blender 显示纯色而不是纹理
- python - Python中的Matlab结构/单元格/单元格数组(不同大小的矩阵)
- azure-logic-apps - 是否有任何 Terraform 代码或 ARM 模板代码可用于在 azure 中将操作作为逻辑应用程序创建操作组
- java - Variables runtime error doubts solve it Runtim
- javascript - How to change showing data?
- vue.js - 如何为单个 vue 文档创建定义?
- google-sheets - FILTER 数组和 COUNTIF/循环计数器
- assembly - 汇编中的“mov”命令
- youtube - YouTube 的 Playlists.list API 端点只返回一项
- python - 不和谐 ping 命令(Python)