Question

How feasible is to do something like this? Consider Enum* a enum Enum* { /* ... */ }...

public static void main(String[] args) {
  ?[] types = new ?[] { Enum1, Enum2, Enum3 };

  for(? type : types) {
    for(Enum elem : type.values() { /* ... */ }
  }
}

My main requirement is basically a bunch of String constants, each one grouped in a different type. Would I be better set with a bidimensional String array (String[][])? I'd like some more constrained values, rather than types[j] where j==1 is A, and j==2 is B.

I know I could play around with reflection, but I dare say it would turn out too complex and then, less readable.

Était-ce utile?

La solution

May be this construction could solve your problem:

    enum SomeEnum {
        A("one", "two", "three"),
        B("hello", "there");

        public final String[] constants;

        SomeEnum(String... constants) {
            this.constants = constants;
        }
    }

Autres conseils

If I understand the question correctly you could create an Enum[][] which would store a list of lists of enums. This would look something like this.

public class Test {

    enum Birds {BIG_BIRD, MEDIUM_BIRD, SMALL_BIRD};
    enum Dogs {BIG_DOG, MEDIUM_DOG, SMALL_DOG};
    enum Bugs {BIG_BUG, MEDIUM_BUG, SMALL_BUG};
    Enum[][] enums = {Birds.values(),Dogs.values(),Bugs.values()};

}

You could then run enums through a nested loop to get the values. Something like;

    for(Enum[] e : enums){ 
        for(Enum e2 : e){ 
            System.out.println(e2);
        }
    }

Which would give you the output;

BIG_BIRD
MEDIUM_BIRD
SMALL_BIRD   
BIG_DOG
MEDIUM_DOG
SMALL_DOG
BIG_BUG
MEDIUM_BUG
SMALL_BUG

You could go even further and declare constants that represented the numerical value that stores the types. Such as;

public static final byte BIRDS = 0;
public static final byte DOGS = 1;
public static final byte BUGS = 2;

Then you could access the specific type from the array by going;

for(Enum e: enums[Test.BIRDS]) System.out.println((Birds)e);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top