用变量定义的数组大小

时间:2017-04-20 16:16:11

标签: java

在Java中是否可以定义一个大小由变量定义的数组,如下所示:

public class MyClass {
    public static class Items{
        int size;
        String[] elements = new String[size];
    }

    public static class Application {
        public doSomething() {
            Items i = new Items();
            i.size = 5;
        }
    }
}

对我来说很奇怪,但我在遗留代码中注意到它,因此我想知道它的语义。

2 个答案:

答案 0 :(得分:1)

数组在创建时具有静态长度(大小)。该长度作为Array.length存储在数组中。

使项目像这样:

public static class Items {
    public Items(int size) {
        elements = new String[size];
    }
    public String[] elements;
}

然后您创建项目项目=新项目(10);

通过执行 myItem .elements.length来检索大小,或者如果您希望元素是私有的,请创建一个getter。

然而除非您打算添加方法,否则此包装器可能不是必需的

答案 1 :(得分:0)

初始化大小变量befor use

public static class Items{
    int size = 15;     // initialize size
    String[] elements = new String[size];
}