Create an array in which each position is an enumeration type

Hi, I would like to create an array in which each position is represented by an enumeration value.

For instance:

public enum type{

  green,blue,black,gray;

}

Now I want to create an array in which each position will be green, blue, ...

I will be more clear. I would like to create an array in which the position is represented by the view enum class.instead int [] array = new int [10] create int [] array = new int [type.value]

+5
source share
5 answers

That type[] allValues = type.values(). See this question .

Alternatively you can use EnumSet:

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

Set, .

PS: enum, (CamelCase).

EDIT:

, , ordinal emum ( - Array ?)

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: , Map<Integer, type> , 0 => green, 1 => blue, 2 => black, 3=> gray ( )?

+6

, , : int.

, , Java Map. , Map<type, Integer> ( EnumMap, Enum).

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

, , ordinal() ( int, , 0):

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

( , , , - BLUE --> 2 BLUE --> 3), :

enum Color {
    GREEN, BLUE, BLACK, GRAY;

    private int value;

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

}

:

Color.BLUE.setValue(8);

:

for (Color c : Color.values()) {
    System.out.println("There are " + c.getValue() + " occurences of " + c);
}
+2

:

 MyColor[] myList;

 myList = new MyColor[20];

nb, type , . - .

0

type? type[] types = type.values()

0

- java.lang.Enum, java.lang.Enum .

enumeration of value (). length displays the size of the enumeration;

enumValue. ordinal () displays the index of the value in the enumeration.

For instance:

public class thisClass {
    enum thisEnum = {valA, valB, valC, valD, valE }
    private int[] arrayForThisEnum;

    public thisClass() {
        this.arrayForThisEnum = new int[thisEnum.values().length];
        // further initialization
    }

    public void addOne(thisEnum xxx) {
        this.arrayForThisEnum[xxx.ordinal()]++;
    }
}
0
source

All Articles