如何修复ArrayList java.lang.IndexOutOfBoundsException:索引20超出长度2的界限
我想在arrayList“colors”中存储没有对的数字,但是我在arrayList中遇到了这个运行时错误。 main获取n(数组大小)的输入和arItems的输入,然后将arItems中的元素转换为整数,将它们放入int数组ar中,然后在调用sockMerchant时传递int n和int数组ar如何修复ArrayList java.lang.IndexOutOfBoundsException:索引20超出长度2的界限,java,runtime-error,indexoutofboundsexception,Java,Runtime Error,Indexoutofboundsexception,我想在arrayList“colors”中存储没有对的数字,但是我在arrayList中遇到了这个运行时错误。 main获取n(数组大小)的输入和arItems的输入,然后将arItems中的元素转换为整数,将它们放入int数组ar中,然后在调用sockMerchant时传递int n和int数组ar static int sockMerchant(int n, int[] ar) { ArrayList<Integer> colors = new ArrayList<
static int sockMerchant(int n, int[] ar) {
ArrayList<Integer> colors = new ArrayList<Integer>(n);
int pairs = 0;
for (int i = 0; i < n; i++) {
if (!colors.contains(ar[i])) {
colors.add(ar[i]);
} else {
pairs++;
colors.remove(ar[i]);
}
}
System.out.println(pairs);
return pairs;
}
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws IOException {
// n is the size of the array
// sample n input: 9
int n = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
int[] ar = new int[n];
//sample arItems input: 10 20 20 10 10 30 50 10 20
String[] arItems = scanner.nextLine().split(" ");
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
for (int i = 0; i < n; i++) {
int arItem = Integer.parseInt(arItems[i]);
ar[i] = arItem;
}
int result = sockMerchant(n, ar);
scanner.close();
}
当您试图从数组
颜色中删除重复项时,您将获得索引自动边界异常
。这是因为ArrayList
的remove()
方法可以接收对象
或int
,并且您正在传递int
。这意味着您实际上正在尝试删除一个特定的索引,在您的示例中,该索引是索引20,但该索引在您的数组中不存在
您可以修改代码,以便根据索引正确删除值
static int sockMerchant(int n, int[] ar) {
ArrayList<Integer> colors = new ArrayList<Integer>(10);
int pairs = 0;
for (int i = 0; i < n; i++) {
if (!colors.contains(ar[i])) {
colors.add(ar[i]);
} else {
pairs++;
colors.remove(color.indexOf(ar[i]));
}
}
System.out.println(pairs);
return pairs;
}
static int(int n,int[]ar){
ArrayList颜色=新的ArrayList(10);
整数对=0;
对于(int i=0;i
嘿,你说没有一对是什么意思。在代码@Janetyeah中添加函数调用很抱歉,我将编辑code@NaveenJain我编辑了代码并将函数调用包含在我的main方法中:),数组中的一个示例输入是10 20 10 30 50 10 20我必须找到数组中有多少对(10有2对,20有1对,30和50没有一对,所以对的数量应该是“3”,这应该是程序的输出)。哦,我忘了remove接受索引参数!!!t^t谢谢你指出这一点
static int sockMerchant(int n, int[] ar) {
ArrayList<Integer> colors = new ArrayList<Integer>(10);
int pairs = 0;
for (int i = 0; i < n; i++) {
if (!colors.contains(ar[i])) {
colors.add(ar[i]);
} else {
pairs++;
colors.remove(color.indexOf(ar[i]));
}
}
System.out.println(pairs);
return pairs;
}