Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 为什么在初始化数组后我不能在数组中赋值?_Java_Arrays - Fatal编程技术网

Java 为什么在初始化数组后我不能在数组中赋值?

Java 为什么在初始化数组后我不能在数组中赋值?,java,arrays,Java,Arrays,这是我的代码,初始化数组后,我无法在数组中重新分配一些值。它显示数组索引越界异常 public class NewClass { public static void main(String args[]){ String cl[]={}; cl[0]="10"; System.out.print(cl.length); } } 我的输出: Exception in thread "main"

这是我的代码,初始化数组后,我无法在数组中重新分配一些值。它显示数组索引越界异常

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

        String cl[]={};
        cl[0]="10";      
        System.out.print(cl.length);        
    }    
}
我的输出:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
    at NewClass.main(NewClass.java:15)
Java Result: 1
创建空数组的实例,因此不能向其中添加任何元素

要创建非空数组,请使用

String cl[] = {"something",...};


如果要声明数组,可以执行以下操作:

String cl[];
之后,您可以通过调用以下命令初始化阵列:

cl = new String[10];

以及您的
系统输出打印(cl.length)将返回您想要的内容。

那么解决方案是什么呢@如果您需要“数组”可扩展,请使用Ram。您的
cl
数组大小为
0
,并且您试图插入值以便
java.lang.ArrayIndexOutOfBoundsException
您可以使用动态列表,例如
list c1=new ArrayList()是否可以在列表中存储数组?
String cl[];
cl = new String[10];