gpt4 book ai didi

java - 为什么我收到错误?

转载 作者:行者123 更新时间:2023-12-01 17:56:45 25 4
gpt4 key购买 nike

 import java.util.*;
public class Nostalgia {
static ArrayList<Integer> arr = new ArrayList<Integer>(5);
static int array[] ={6,3,6,2,3};
//static int num;
public static void main(String args[]){
Scanner s = new Scanner(System.in);

arr.set(0, 8);
arr.set(1, 4);
arr.set(3, 6);
arr.set(2, 9);
arr.set(4, 7);
arr.set(5, 1);


System.out.print(3+" :"+arr.get(3));

}
}

我收到此错误。

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 0

at java.util.ArrayList.rangeCheck(Unknown Source) at java.util.ArrayList.set(Unknown Source) at Nostalgia.main(Nostalgia.java:9)

我正在尝试将一些值放入列表中并在特定索引处显示值。

最佳答案

问题是您在空列表上调用 SET(x,y),而 set 执行 this :

Replaces the element at the specified position in this list with the specified element

但是set方法实际上是一个替换操作...java如何替换一个不存在的元素..

而不是在空列表上设置元素:

arr.set(0, 8);
arr.set(1, 4);
arr.set(3, 6);

您应该将它们添加到列表中

arr.add(0, 8);
arr.add(1, 4);

但是要小心,您不能添加超出列表实际大小的元素!

关于java - 为什么我收到错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44152939/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com