简体   繁体   English

为什么在初始化数组后我无法在数组中分配一些值?

[英]Why after initializing the array I cannot assign some value in array?

This is my code, after initialized the array, I cannot able to reassign some value in array. 这是我的代码,在初始化数组后,我无法在数组中重新分配一些值。 It shows array index out of bound exception. 它显示数组索引超出绑定的异常。

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

        String cl[]={};
        cl[0]="10";      
        System.out.print(cl.length);        
    }    
}

my output: 我的输出:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
    at NewClass.main(NewClass.java:15)
Java Result: 1
String cl[]={};

Creates an instance of an empty array, so you can't add any elements to it. 创建一个空数组的实例,因此您无法向其中添加任何元素。

In order to create a non empty array, use either 要创建非空数组,请使用其中一个

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

or 要么

String cl[] = new String[theArrayLength];

If you want to declare your array, you can do something like this: 如果要声明数组,可以执行以下操作:

String cl[];

After that you can initialize your array by calling this: 之后,您可以通过调用以下内容来初始化您的数组:

cl = new String[10];

And your System.out.print(cl.length); 和你的System.out.print(cl.length); will return what you want. 会回报你想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM