gpt4 book ai didi

java - 获取 IndexOutOfBoundException

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:12:57 27 4
gpt4 key购买 nike

为什么下面的 main 方法在 list.add(1, 2) 处给出 IndexOutOfBoundException?

public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
list.add(1, 2);
int total = list.get(0);
System.out.println(total);
}

最佳答案

当 ArrayList 为空时,您不能在索引 1 处添加元素。它从 0 开始,或者只使用添加。

public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
int total = list.get(0); // <-- You even use 0 here!
System.out.println(total);
}

根据 ArrayList#add(int index, E element) javadoc ,

Throws:

  IndexOutOfBoundsException - if the index is out of range 
(index < 0 || index > size())

当 size == 0 时,索引 1 超出范围。

关于java - 获取 IndexOutOfBoundException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24847257/

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