4

This is the code:

// Default constructor
public Bestellung() {
    this(null, null, null);
}

// Initial constructor
public Bestellung(LocalDateTime zeitstempelBestellung, LocalDateTime zeitstempelAuslieferung,
        PizzaVO[] warenkorb, int index) {
    super(); 
    this.zeitstempelBestellung = zeitstempelBestellung;
    this.zeitstempelAuslieferung = zeitstempelAuslieferung;
    this.warenkorb = warenkorb;
    this.index = index;
}

I'd like to finish the default constructor. Therefore I have to pass two localDateTimes, one empty array and one int to the constructor. How do I pass the empty array?

7 Answers 7

9

How do I pass the empty array?

new PizzaVO[] { }

BTW, this is not a default constructor:

public Bestellung() {
    this(null, null, null);
}

it is a no-argument constructor.

Sign up to request clarification or add additional context in comments.

Comments

2

Creating of empty array is exactly as creating of regular array with 0 size: new PizzaVO[0].

so, you constructor will look like:

public Bestellung() {
    this(null, null, new PizzaVO[0], 0);
}

(you have not mentioned how do you want to initialize LocalDataTime objects, so I passed null)

Comments

1

Like this:

public Bestellung() {
    this(null, null, new PizzaVO[]{}, 1);
}

Comments

1

Just make:

this.warenkorb = new PizzaV0[10];

This will initialize an empty array with 10 nulls.

Comments

1

I am not sure I quite understand what you are trying to do or what you want to achieve, perhaps you could be a bit clearer?

You can do as you are doing now and pass null (although this isn't an empty array) or you can pass an actual empty array new PizzaVO[0] (which is an array of PizzaVOs with no space for any elements).

public Bestellung() {
    this(null, null, null, 0);
}

or

public Bestellung() {
    this(null, null, new PizzaVO[0], 0);
}

Is one of those what you are looking for? Or did I completely misunderstand something?

Comments

0

Well, you use "null" for all our other elements; that will create a Bestellung object which is most likely useless; as it will most likely fail on a NullPointerException the first time you want to do something with it (like calling one of its methods).

So what prevents you from using "null" for the array as well.

Ok, the serious answer is that you can create arrays with

new PizzaVO[] {}

for example.

And the really serious answer is still: typically, there is no sense in having all-nulled objects most of the time. So you should not implement your default constructor this way.

In other words: if your object can't be created without real existing parameters ... then don't provide a constructor that allows users to actually do that.

Comments

0

You can pass an empty array argument like this

new PizzaVO[0]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.