0

I see that obviously java does not allow to pass arrays directly to methods (didn't know this before). For example this does not compile:

public static void main(String[] args) {
    testFunk({1,2,3,4});
}

public static void testFunk(int[] a) {}

But this does:

public static void main(String[] args) {
    int[] a = {1,2,3,4};
    testFunk(a);
}

public static void testFunk(int[] a) {}

But what if i need to create an enum with a constructor that accepts an array?

For example I tried the following code, but it does not compile for the same reason as above:

    public enum FigureType {

    SQUARE({{true, true},{false, false}});

    private boolean[][] matrix;

    private FigureType(boolean[][] matrix) {
        this.matrix = matrix;
    }

}

Unfortunately there does not seem to be a simple workaround here. The only option that comes to my mind is to build something like this:

    public enum FigureType {

    SQUARE(() -> {boolean[][] array = {{true,true},{false,false}}; return array; });

    private boolean[][] matrix;

    private FigureType(Supplier<boolean[][]> supplier) {
        this.matrix = supplier.get();
    }

}

But this looks quite ugly ... is there some better solution?

Thanks and greetings, Daniel

4 Answers 4

10

You can pass arrays directly to methods. If you want to initialise an array and pass it to a method in one line, you need this:

testFunk(new int[] {1,2,3,4});

instead of this

testFunk({1,2,3,4});
Sign up to request clarification or add additional context in comments.

Comments

1

If providing array values as literals is your primary concern you could use:

  • varargs / ellipsed: boolean...
  • make the parameter a list and use Arrays.asList()

As well.

Comments

1

You can initialize the array directly inline with the new keyword:

public enum FigureType {

    SQUARE(new boolean[][]{{true, false}, {false,true}});

    FigureType(boolean[][] array){ ... }

}

To mention is that inside a 2D array the short array initializer ({}) can be used.

Comments

0

By passing a list of elements as a parameter does not makes sense until you wrap in some structure(object) and initialize that through the new operator.

So, instead of : SQUARE({{true, true},{false, false}});

Do : SQUARE(new boolean[][] {{true, true},{false, false}});

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.