Java - 在构造函数中初始化数组

时间:2017-03-23 14:23:47

标签: java arrays constructor

我想在构造函数中初始化二维数组。但是,当我在类中声明数组的实例变量时,我遇到了问题。如果我这样做会是错误的:

public class Data {
private String [][] tabel;
public Data(){
    tabel = {{"ID", "NAME"},
             {"101", "Max"},
             {"102", "Mark"},
             {"103", "Downey"},
             {"104", "Matthew"},
             {"105", "Richard"}};
}

我如何解决这个问题?

1 个答案:

答案 0 :(得分:4)

您需要在数组初始值设定项前写new Type[],如下所示:

tabel = new String[][]{
            new String[]{"ID", "NAME"},
            new String[]{"101", "Max"},
            new String[]{"102", "Mark"},
            new String[]{"103", "Downey"},
            new String[]{"104", "Matthew"},
            new String[]{"105", "Richard"}};