当数组在创建它的类之外定义时,为什么“数组常量只能在初始化器中使用”

时间:2013-11-05 00:21:31

标签: java arrays

我将String数组设置在另一个类中但是当我尝试以某种方式设置该值时,它将返回“数组常量只能在初始化器中使用”。

import java.util.Scanner;

class People {

    String[] names;
    int age;
    int height;

}

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

        People person1 = new People();

        People person2 = new People();

        People person3 = new People();

        // I can set the values like this.

        person1.names[0] = "Joe";
        person1.names[2] = "!";
        person1.names[3] = "?";

        // But not like the more effective way.
        person2.names = {"Apple", "Banana"};

        person1.age = 13;
        person1.height = 164;

    }
}

1 个答案:

答案 0 :(得分:2)

以下语法用于在声明行以外的行上实例化数组:

person2.names = new String[] {"Apple", "Banana"};