(单一情况!)我一直收到这个错误:线程“main”中出现异常java.lang.IndexOutOfBoundsException:索引0超出长度0的界限[重复]

k5ifujac  于 2023-01-16  发布在  Java
关注(0)|答案(1)|浏览(159)
    • 此问题在此处已有答案**:

What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?(26个答案)
2天前关闭。
大家好,我是Java新手,我在VSCode上遇到了这个错误:线程"main"中出现异常java. lang. IndexOutOfBoundsException:索引0超出长度0的范围这是什么意思?
这是我的代码,我认为我已经做了所有的权利,到目前为止。这是一个教程从YT:

import java.util.ArrayList;

public class ArrayList1 {
    public static void main(String[] args) {

        // ArrayList = a resizeable array.
        // Elements can be added and removed after compilation phase.
        // store reference data types

        ArrayList<String> names = new ArrayList<String>();

        names.set(0, "Ramunas"); // changes the value of a ArrayList.
        names.remove(2); // removes 'Halil' from the ArrayList.
        // names.clear(); // clears the entire 'names' ArrayList.

        names.add("Tomas");
        names.add("Rizgar");
        names.add("Halil");

        for (int i = 0; i < names.size(); i++) {
            System.out.println(names.get(i));
        }

    }
}

.........................................

dgenwo3n

dgenwo3n1#

您的问题很简单,您必须先添加名称

public class ArrayList1 {
  public static void main(String[] args) {

    // ArrayList = a resizeable array.
    // Elements can be added and removed after compilation phase.
    // store reference data types

    ArrayList<String> names = new ArrayList<String>();

    names.add("Tomas");
    names.add("Rizgar");
    names.add("Halil");

    names.set(0, "Ramunas"); // changes the value of a ArrayList.
    names.remove(2); // removes 'Halil' from the ArrayList.
    // names.clear(); // clears the entire 'names' ArrayList.

    for (int i = 0; i < names.size(); i++) {
        System.out.println(names.get(i));
    }

  }
}

相关问题