gpt4 book ai didi

Java - 是否可以在不使用 ArrayList 的情况下防止数组中出现重复项?

转载 作者:行者123 更新时间:2023-12-01 09:29:59 25 4
gpt4 key购买 nike

我正在尝试创建一个代码来防止重复的数组元素。无论如何,我可以在不创建 arrayList 的情况下做到这一点吗?

运行程序时,当我输入第一个 #: 时会发生此错误

线程“main”中的异常 java.lang.ArrayIndexOutOfBoundsException: -1 在 DuplicateElimination.main(DuplicateElimination.java:32)

这是我的代码:

int[] numList = new int[5];
int newValue;
boolean invalid;

for (int i = 0; i < numList.length; i++){
do{
System.out.print("Please enter number");
System.out.println(" ");
newValue = input.nextInt();

//This is where the error occurs when I try to compare
//The last list element to the input value
invalid = numList[i-1] == newValue;

if(newValue < 10 || newValue > 100){
System.out.print("Invalid number, Please enter a number between 10 and 100");
newValue = input.nextInt();
}
if(invalid){
System.out.print("That number was entered already try again");
}
}while(invalid);

insertIntoArray(numList, i, newValue);
printArray(numList);
}

最佳答案

您可以通过以下方式防止集合中出现重复

  1. 使用具有合理 equals 方法的类
  2. 然后使用集合;因为这些本质上会阻止您“收集”重复项

另一种方式是:在添加new元素之前;您只需迭代完整的现有数组即可查看它是否已包含要添加的内容。如果是这样,您的代码将拒绝添加已知的"new"元素。

本质上:你绝对不需要“第二个”ArrayList 来做到这一点。如果您的应用程序的全部目的是“收集”某些不重复的对象,那么您只需使用 Set 即可。您只需踢出阵列即可;你只需使用一个集合。

关于Java - 是否可以在不使用 ArrayList 的情况下防止数组中出现重复项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39516866/

25 4 0