user2849447
user2849447

Reputation:

Passing Hard-coded Array Values to Constructor

Is there a way to specify a constructor that takes in an array, and then pass directly to that constructor a list of predefined values for that array.

Here's an example:

Say you have a enum called Unit.

public enum Unit {

    PROBE   (null),
    STALKER (null);

    private final String[] require;

    Unit(String[] require) {
        this.require  = require;
    }

    public String[] require() { return require; }
}

The following code above is valid but what if I wanted to replace the nulls with a list of values?

For example, here's what I'd like to do but it is invalid:

public enum Unit {

    PROBE    (null),
    STALKER  ({"cybernetics core"});

    private final String[] require;

    Unit(String[] require) {
        this.require  = require;
    }

    public String[] require() { return require; }
}

This time, in the above example, I'm trying to pass in one array element value to the constructor. I realize I could specify an array to store this value e.g. String[] stalker = {"cybernetics core"}; but considering that in my full project I require varying array values to be inputted here, I was looking for a more elegant way. Is there?

Upvotes: 1

Views: 4057

Answers (3)

nd.
nd.

Reputation: 8932

In addition to using an array constructor new String[] {} you could also use varargs for your Enum-Constructor:

public enum Unit {

  PROBE    (),
  STALKER  ("cybernetics core");

  private final String[] requirements;

  Unit(String... requirements) {
      this.requirements  = requirements;
  }

  public String[] requirements() { return requirements; }
}

Behind the scenes, Java creates an array for the varargs, but it is nicer to read in the code. Note that, however, an empty parameter leads to an empty array, analogous to new String[0]. In many cases an empty array is much nicer to deal with than null as you don't need null-checks in your code.

Upvotes: 1

Mena
Mena

Reputation: 48404

Your String array initialization will not compile as such.

Just replace:

STALKER  ({"cybernetics core"});

with

STALKER  (new String[]{"cybernetics core"});

Upvotes: 1

Robin Krahl
Robin Krahl

Reputation: 5308

You can use a regular array constructor:

STALKER(new String[] { "value1", "value2" });

Upvotes: 6

Related Questions