Assume we have two or more enums and one Set containing all enum elements, like in:
import java.util.Map;
import java.util.Set;
import java.util.HashSet;
public class Foo {
interface FooEnum {}
enum FooEnum1 implements FooEnum {
K1,
K2
}
enum FooEnum2 implements FooEnum {
K3,
K4
}
static public Set<FooEnum> all = new HashSet<FooEnum>();
public static void main(String [] args) {
Foo it = new Foo();
it.all.add( FooEnum1.K1 );
it.all.add( FooEnum1.K2 );
it.all.add( FooEnum2.K3 );
it.all.add( FooEnum2.K4 );
for( FooEnum k : it.all ) {
System.out.println( k.toString() );
}
}
}
it is possible to fill the all
set without one "add" for each set member NOR A LOOP for each enum (outside the enum itself) ? That is, fill it inside an enum constructor or static code?
** Addendum **
In other words, the objective is that addition of one enum element or addition of a new enum that implements FooEnum doesn't needs new lines of code to fill the set (that a programmer could forget causing an error).
Better, if initialization of "add" is done in constructors or static code.
** Addendum 2 **
Following code is similar to what is expected, but doesn't produces the expect result:
import java.util.Map;
import java.util.Set;
import java.util.HashSet;
public class Foo {
interface FooEnum {
}
static public Set<FooEnum> all = new HashSet<FooEnum>();
enum FooEnum1 implements FooEnum {
K1,
K2;
FooEnum1() {
all.add(this);
}
}
enum FooEnum2 implements FooEnum {
K3,
K4;
FooEnum2() {
all.add(this);
}
}
public static void main(String [] args) {
Foo it = new Foo();
for( FooEnum k : it.all ) {
System.out.println( k.toString() );
}
}
}
following one fails also:
import java.util.Map;
import java.util.Set;
import java.util.HashSet;
public class Foo {
interface FooEnum {
}
enum FooEnum1 implements FooEnum {
K1,
K2;
static {
for( FooEnum1 e : FooEnum1.values() ) {
all.add(e);
}
}
}
enum FooEnum2 implements FooEnum {
K3,
K4;
static {
for( FooEnum2 e : FooEnum2.values() ) {
all.add(e);
}
}
}
static public Set<FooEnum> all = new HashSet<FooEnum>();
public static void main(String [] args) {
Foo it = new Foo();
for( FooEnum k : Foo.all ) {
System.out.println( k.toString() );
}
}
}