【问题标题】:Java - Initialize array in constructor [duplicate]Java - 在构造函数中初始化数组[重复]
【发布时间】:2017-08-16 04:07:41
【问题描述】:

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

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

我该如何解决这个问题?

【问题讨论】:

  • 在每个 {} 块之前添加新的 String[]
  • 如果不和声明在同一行,需要使用new
  • 错误是什么?

标签: java arrays constructor


【解决方案1】:

您需要在数组初始值设定项前写上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"}};

【讨论】:

    猜你喜欢
    • 2018-08-02
    • 2018-09-25
    • 1970-01-01
    • 2017-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多