当我使用 for-each 循环和 switch 语句迭代一个简单的 Enum 测试器以输出枚举值时,我看到的行为对我来说似乎很奇怪。
代码:
public class EnumTest {
private Number number;
public EnumTest(Number number) {
this.number = number;
}
public enum Number {
ONE,
TWO,
THREE,
FOUR,
FIVE;
}
private void tellItLikeItIs() {
switch (number) {
case ONE:
System.out.println("ONE");
case TWO:
System.out.println("TWO");
case THREE:
System.out.println("THREE");
case FOUR:
System.out.println("FOUR");
case FIVE:
System.out.println("FIVE");
}
}
public static void main(String[] args) {
for (Number n : Number.values()) {
EnumTest et = new EnumTest(n);
et.tellItLikeItIs();
System.out.println();
}
}
}
输出:
ONE
TWO
THREE
FOUR
FIVE
TWO
THREE
FOUR
FIVE
THREE
FOUR
FIVE
FOUR
FIVE
FIVE
为什么每个调用都返回自身和所有后续值?