Reputation: 1075
I use enum to indicate a type and subtype.
enum Type {
TYPE1(1),
TYPE2(2),
...
private int constant;
Type(int constant) {
this.constant = constant;
}
}
enum SubType {
SUBTYPE1(1),
SUBTYPE2(2),
SUBTYPE3(3),
...
private int constant;
SubType(int constant) {
this.constant = constant;
}
}
Each type has a different subtype.
For example TYPE1 has subtypes SUBTYPE1 and SUBTYPE2, TYPE2 has subtypes SUBTYPE2 and SUBTYPE3.
What structure should I use to represent this relationship?
I thought of using map. e.g Map<Type, List<SubType>>
Is there any other way?
Upvotes: 2
Views: 457
Reputation: 27946
You have a number of options here:
you could use a map as you say. Ideally this would be EnumMap<Type,List<Subtype>>
to take advantage of the efficiencies of EnumMap
.
explicitly make retrieving subtypes a method of the types. That would mean adding a method (e.g. Stream<Subtype> getSubtypes()
) to the enum which is overriden for each type.
Store the 'owner' type with the subtype.
enum Subtype { SUBTYPE1(TYPE1), SUBTYPE2(TYPE1), SUBTYPE3(TYPE2)...
private final Type parent;
public static Stream<Subtype> getSubtypes(Type type) {
return Arrays.stream(values()).filter(st -> st.parent.equals(type));
}
private Subtype(Type parent) {
this.parent = parent;
}
}
Upvotes: 0
Reputation: 824
Assuming the Type and Subtype infrastructure is constant, you could always attach a list of Subtypes to the Type enum.
enum Type {
TYPE1(1, Arrays.asList(SubType.SUBTYPE1, SubType.SUBTYPE2)),
TYPE2(2, Arrays.asList(SubType.SUBTYPE3),
...
private int constant;
public final List<SubType> subtypes;
Type(int constant, List<SubType> subtypes) {
this.constant = constant;
this.subtypes = subtypes;
}
}
enum SubType {
SUBTYPE1(1),
SUBTYPE2(2),
SUBTYPE3(3),
...
private int constant;
SubType(int constant) {
this.constant = constant;
}
}
That might provide a more elegant way to access the subtypes of a Type.
As a side note, it's a good idea to use something like Arrays.asList() to define these mappings to ensure that the 'subtypes' list is immutable.
Upvotes: 3
Reputation: 1592
One way would be to extend your parent enums something like this:
public interface Type1{
enum SubType1 implements Type1 {
}
enum SubType2 implements Type1{
}
}
public interface Type2{
enum SubType1 implements Type2 {
}
enum SubType2 implements Type2{
}
}
Upvotes: 0