I have the Enum A, B, C. In a method, I am given two different Enum and must return the remaining Enum.
Example: I receive A and C I must return B
The solution that I have is to use if elseif else:
private EnumABC findRemaining(EnumABC pEnum1, EnumABC pEnum2){
if((pEnum1 == EnumABC.A || pEnum2 == EnumABC.A)
&& (pEnum1 == EnumABC.B || pEnum2 == EnumABC.B)){
return EnumABC.C;
} else
if((pEnum1 == EnumABC.A || pEnum2 == EnumABC.A)
&& (pEnum1 == EnumABC.C || pEnum2 == EnumABC.C)){
return EnumABC.B;
} else{
return EnumABC.A;
}
}
I was wondering if there was a more readable solution then this.
enum Animal { DOG , CAT , BIRD }
EnumSet<Animal> flyingAnimals = EnumSet.complementOf ( EnumSet.of( DOG , CAT ) )
EnumSet.complementOf
You can make a Set
of enum objects. Indeed, you can make a highly performant EnumSet
.
enum Animal { DOG , CAT , BIRD }
EnumSet<Animal> furry = EnumSet.of( DOG , CAT ) ;
Ask for those enum objects not found in an EnumSet
by calling the static
method EnumSet.complementOf
.
EnumSet<Animal> nonFurry = EnumSet.complementOf ( furry ) ;
Tip: You can define an enum
locally in modern Java. Ditto for interface
and record
.