Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using arrays in enums Java

Tags:

java

arrays

enums

A part of my Java assignment requires me to create an enumeration which represents four different types of masks (shapes) which cover squares of a game board. The masks are 3x3 in measurement, with some squares of the 3x3 block missing (these do not hide squares on the game board).

1 0 1  //you can think of the 0's as missing squares, and the 1's as the mask
1 1 1
1 1 0

Now I want to attach a binary matrix to like above to each of the four unique masks using arrays like int[][], like so:

public enum Mask {
    W([[1,1,0],[1,1,1],[1,0,1]]),
    X([[1,0,1],[1,0,1],[1,1,1]]),
    Y([[0,1,1],[1,1,1],[1,1,0]]),
    Z([[1,0,1],[1,1,1],[1,0,1]]);

My IDE becomes very unhappy when I try to do this, so I'm sure I'm missing something in my understanding of enums/arrays.

I'm guessing I can't initialize the array in the enum or something like that?

How do I implement this idea?

like image 714
420fedoras Avatar asked Aug 09 '17 11:08

420fedoras


People also ask

Can we use array in enum?

Enums are value types (usually Int32). Like any integer value, you can access an array with their values. Enum values are ordered starting with zero, based on their textual order. MessageType We see the MessageType enum, which is a series of int values you can access with strongly-typed named constants.

Can we have array of enum in Java?

You can iterate through an enum to access its values. The static values() method of the java. lang. Enum class that all enums inherit gives you an array of enum values.

Can you have an ArrayList of enums?

Using an ArrayList of Enum Values. We can also create an ArrayList by using Arrays. asList().


1 Answers

My IDE becomes very unhappy when I try to do this

yes, that is because you are giving the array wrong..

you just cant do this:

W([[1,1,0],[1,1,1],[1,0,1]]),

is not valid and the compiler has no idea that you are "trying to pass" an array as argument, at the end you are just trying to give as parameter an array (in your case an annonymous one), so you have to use a syntax of the form

W(new int[] { 1, 1 });

see this exaplem below as an orientation point:

enum Mask {
    W(new int[] { 1, 1 });
    private final int[] myArray;

    private Mask(int[] myArray) {
        this.myArray = myArray;
    }

}
like image 98
ΦXocę 웃 Пepeúpa ツ Avatar answered Nov 15 '22 04:11

ΦXocę 웃 Пepeúpa ツ