Search code examples
javaenumsinstantiationcross-reference

Enums that cross reference each other produce different results depending on order called


I have two enums that cross reference each other. Each one has a constructor that has a parameter for other enum.

They look something like:

SchoolEnum(ImmuneEnum value)
{
   this.immune = value;
}

ImmuneEnum(SchoolEnum value)
{
   this.school = value;
}

However depending on which Enum I call first, I can get a null value for the reference variable.

ImmunityEnum immune = ImmunityEnum.IMMUNE_KANNIC; 
SchoolEnum school = SchoolEnum.KANNIC;
System.out.println(school.getImmune())
System.out.println(immune.getSchool());

Produces the output: null Kannic

SchoolEnum school = SchoolEnum.KANNIC;
ImmunityEnum immune = ImmunityEnum.IMMUNE_KANNIC; 
System.out.println(school.getImmune())
System.out.println(immune.getSchool());

Produces the output: immunekannic null

It seems to be a bit of the "chicken and egg" problem as to when the enum is instantiated. But is there a way to have each one properly reference the other? I am considering making two singleton hashmaps that artificially cross reference the two, but is there a better idea?


Solution

  • What if you passing String parameters into your constructors:

    public enum SchoolEnum {
       Kannic("immnunekannic");
       private String immune;
       public SchoolEnum (String immune) {this.immune = immune;}
       public ImmuneEnum getImmune() {
           return ImmuneEnum.valueOf(immune);
       }
    }
    
    public enum ImmnueEnum {
       immunekannic("Kannic");
       private String scholl;
       public ImmnueEnum (String school) {this.school = school;}
       public SchoolEnum getSchool() {
           return SchoolEnum.valueOf(school);
       }
    }
    

    But honestly it's a bit strange to create this type of domain model. What's your use case?