Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an array in which every position is an enum type

Tags:

java

arrays

enums

Hi I would like to create an array in which every position is represented by the value of an enum.

For instance:

public enum type{

  green,blue,black,gray;

}

Now i want to create an array in which every position is green,blue,...

I'll be clearer. I would like to create an array in which the position is rapresented by a value of enum class.instead int[] array = new int[10] create int[] array = new int[type.value]

like image 791
Mazzy Avatar asked Dec 11 '11 22:12

Mazzy


2 Answers

It's type[] allValues = type.values(). See this question.

Alternatively you can use EnumSet:

EnumSet<type> types = EnumSet.allOf(type.class);

which gives you high-performance Set implementation filled with your enum's values.

PS: You should name enum class beginning with big letter (CamelCase).

EDIT:

Seems you want array of ordinal positions of your emum's values (why would anybody use an Array instead of right Collection nowadays?):

type[] colors = type.values();
List<Integer> list = new ArrayList<Integer>(colors.length);
for (type color : colors) {
  list.add(color.ordinal());
}
Integer[] array = list.toArray(new Integer[0]);

EDIT2: Maybe you want Map<Integer, type> with keys and values like 0 => green, 1 => blue, 2 => black, 3=> gray (the question still isn't clear)?

like image 81
Xaerxess Avatar answered Nov 11 '22 20:11

Xaerxess


Please first correct me if I'm wrong: you're trying to associate each color with an int value.

If so, what you're looking for is an associative array, which in Java is modelled as a Map. So you can use some Map<type, Integer> to achieve what you want (preferably an EnumMap which is optimized for using Enum keys).

// I renamed your "type" to Color
Map<Color, Integer> map = new EnumMap<Color, Integer>(Color.class);
map.put(Color.BLUE, 3);

However, if you really want to use an array, you can make use of the ordinal() method of your enum constants (which returns an int representing the constant's position in the enum declaration, starting from 0):

int[] ints = new int[Color.values().length];
ints[Color.BLUE.ordinal()] = 3;

If this association is meant to be unique for your entire application (if you never need to associate a color with more than one value at the same time; in other words, if it's never the case that some client stores BLUE --> 2 and some other stores BLUE --> 3), then it would be better to store that value in the enum itself:

enum Color {
    GREEN, BLUE, BLACK, GRAY;

    private int value;

    // ...getter and setter for value...

}

Then you can write:

Color.BLUE.setValue(8);

And for reading the values:

for (Color c : Color.values()) {
    System.out.println("There are " + c.getValue() + " occurences of " + c);
}
like image 43
Costi Ciudatu Avatar answered Nov 11 '22 19:11

Costi Ciudatu