gpt4 book ai didi

java - 为什么我的程序抛出 "IndexOutOfBoundsException",索引为 : 1, Size: 0

转载 作者:行者123 更新时间:2023-12-02 01:05:36 25 4
gpt4 key购买 nike

我正在用 Java 为 D&D 制作一个主动跟踪器,由一个由随机整数填充的 Arraylist 组成。但是,当我尝试读取 ArrayList 的给定索引时,程序会抛出异常:

import java.util.ArrayList;
import java.util.Random;

public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

System.out.println("Add number of enemies");

int a = sc.nextInt();

ArrayList<Integer> initiativeList = new ArrayList<>(a); // This is where i have added it, code was not updated.

Random rand = new Random();
for (int i = 1; i <= a; i++) { // adding a given number to Arraylist
int initRoll = rand.nextInt(19);
initiativeList.add(i, initRoll);
System.out.println(initRoll);
}
int q = initiativeList.get(3);
System.out.println(q);


}
}

我已将 ArrayList 的大小设置为等于 int a,它接受用户输入。

最佳答案

您将数组列表的大小与其容量混淆了:

  • 大小是列表中元素的数量;
  • 容量是列表在不重新分配其内部结构的情况下可以容纳的元素数量。

下面的初始化显示了数组列表的容量(列表可以容纳多少个元素) -

ArrayList<Integer> initiativeList = new ArrayList<>(a);//here  you are not setting size of list, you are setting list capacity to a.

这就是为什么你的代码抛出越界异常,因为它的大小实际上是 0。

希望这有帮助。

关于java - 为什么我的程序抛出 "IndexOutOfBoundsException",索引为 : 1, Size: 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60092543/

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