0

I've looked everywhere and I haven't found anything related to initializing an array in a class constructor.

This is the class I'm trying to create:

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

This is my attempt at initializing the array:

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();
}

I am at a loss.

Cœur
  • 37,241
  • 25
  • 195
  • 267
DrSooch
  • 312
  • 1
  • 11

2 Answers2

1

Option 1: Use new to make and array:

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

Option 2: Use VarArgs:

Redefine your constructor as:

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

Passing values to constructor, 4th parameter onwards, all are array elements:

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

Can you try this:

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

Refer java tutorial About array

mcacorner
  • 1,304
  • 3
  • 22
  • 45