【问题标题】:How to initialize an array in a class constructor [duplicate]如何在类构造函数中初始化数组[重复]
【发布时间】:2018-09-25 18:31:00
【问题描述】:

我到处寻找,但没有找到与在类构造函数中初始化数组相关的任何内容。

这是我要创建的类:

 public Sandwich(char b, String m, String c, String[] e)
 {
    setBread( b );
    setMeat( m );
    setCheese( c );
    setExtras( e );
 }

这是我初始化数组的尝试:

public static void main(String[] args)
{
    Sandwich[] order;
    order = new Sandwich[3];

    order[0] = new Sandwich('s', "pastrami", "swiss", extras[2] = {"mayo", "extra meat"}  )
    order[1] = new Sandwich();
}

我很茫然。

【问题讨论】:

    标签: java arrays class constructor initialization


    【解决方案1】:

    你能试试这个吗:

    order[0] = new Sandwich('s', "pastrami", "swiss", new String[]{"mayo", "extra meat"} );
    

    参考java教程About array

    【讨论】:

      【解决方案2】:

      选项 1:使用new 制作和排列:

      new Sandwich('s', "pastrami", "swiss", new String[]{"mayo", "extra meat"});
      

      选项 2:使用 VarArgs:

      将你的构造函数重新定义为:

      public Sandwich(char b, String m, String c, String... e)
      

      给构造函数传值,从第4个参数开始,都是数组元素:

      new Sandwich('s', "pastrami", "swiss", "mayo", "extra meat");
      new Sandwich('s', "pastrami", "swiss", "mayo", "extra meat", "cheese");
      

      【讨论】:

        猜你喜欢
        • 2017-08-16
        • 1970-01-01
        • 1970-01-01
        • 2018-08-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-12
        相关资源
        最近更新 更多