In Java switch statement, when enum is used as an expression, qualified name is not given. It was strange that the compilation passed when there were two or more same constants, so I checked it. First of all, no modification is required, so you can use it as it is without worrying about it.
Suppose you have an enum like this.
FoodType.java
public enum FoodType {
RICE,
BREAD,
OTHER,
}
Main.java
import lombok.AllArgsConstructor;
public class Main {
public static void main(String[] args) {
Food food = new Food(FoodType.RICE);
switch (food.foodType){
case RICE:
System.out.println("Solder");
break;
case BREAD:
System.out.println("It's bread");
break;
default:
System.out.println("Other");
break;
}
}
}
@AllArgsConstructor
class Food {
FoodType foodType;
}
On the Main side, the enum (FoodType) is branched by the switch statement.
In this case, write the case as RICE
instead of FoodType.RICE
.
(Why RICE is good will be explained later.)
Let's add an enum to the code above. Suppose you want to subdivide the rice category.
RiceType
public enum RiceType {
RICE,
FriedRice,
}
Main also changed.
Main.java
import lombok.AllArgsConstructor;
public class Main {
public static void main(String[] args) {
Food food = new Food(FoodType.RICE,RiceType.RICE);
switch (food.foodType){
case RICE:
switch (food.riceType){
case RICE:
System.out.println("Solder");
break;
case FriedRice:
System.out.println("It's fried rice");
break;
}
break;
case BREAD:
System.out.println("It's bread");
break;
default:
System.out.println("Other");
break;
}
}
}
@AllArgsConstructor
class Food {
FoodType foodType;
RiceType riceType;
}
The above code will compile.
This is correct code, but I was wondering if case RICE:
and case RICE:
would compile without conflict in the following parts of Main:
Also, import is not used because all the code is included.
switch (food.foodType){
case RICE:
switch (food.riceType){
case RICE:
Upon examination, the class names are now qualified at compile time, so the names don't seem to conflict. It's a bit old, but you can see the result of decompiling enums in the "Implementing a switch" section of the following site. http://www.ne.jp/asahi/hishidama/home/tech/java/enum.html#h2_switch
It was a mechanism that was qualified at compile time.
Recommended Posts