跟我学 Java – Java 枚举示例讲解
enum,比如一周中的天数、一年中的季节、颜色等等。enum以及如何将其值赋给其他变量。我们还将看到如何在switch语句中使用 enum 或循环遍历它的值。如何在 Java 中创建枚举
enum,我们使用enum关键字,类似于使用 class 关键字创建类的方式。
enum Colors { RED, BLUE, YELLOW, GREEN}
Colors 的枚举。您可能会注意到这个枚举的值都是大写的—这只是一个通用的约定。如果值是小写的,您将不会收到错误。
enum Colors { RED, BLUE, YELLOW, GREEN}
public class Main { public static void main(String[] args) { Colors red = Colors.RED; System.out.println(red); // RED } }
Colors 变量,并将枚举的一个值赋给它:Colors red = Colors.RED;。Main类内部创建枚举,代码仍然可以工作。那就是:public class Main { enum Colors { RED, BLUE, YELLOW, GREEN} public static void main(String[] args) { Colors red = Colors.RED; System.out.println(red); } }ordinal()方法。下面是一个例子
enum Colors { RED, BLUE, YELLOW, GREEN}
public class Main { public static void main(String[] args) { Colors red = Colors.RED; System.out.println(red.ordinal()); // 0 } }
red.ordinal() 返回0。如何在 switch 语句中使用枚举
switch语句中使用 enum。
public class Main { enum Colors { RED, BLUE, YELLOW, GREEN } public static void main(String[] args) { Colors myColor = Colors.YELLOW;
switch(myColor) { case RED: System.out.println("The color is red"); break; case BLUE: System.out.println("The color is blue"); break; case YELLOW: System.out.println("The color is yellow"); break; case GREEN: System.out.println("The color is green"); break; } } }
switch 语句中使用 enum 的非常基本的例子。我们将在控制台中打印“The color is yellow”,因为这是符合switch语句条件的情况。如何循环遍历枚举的值
enum在 Java 中有一个values()方法,它返回枚举值的数组。我们将使用 for-each 循环遍历并打印枚举的值。
enum Colors { RED, BLUE, YELLOW, GREEN}
public class Main { public static void main(String[] args) { for (Colors allColors : Colors.values()) { System.out.println(allColors); /* RED BLUE YELLOW GREEN */ } } }
结论
enum 是什么,如何创建它,以及如何将它的值赋给其他变量。switch语句中使用 enum 类型,以及如何循环遍历 enum 的值。来自:Linux迷
链接:https://www.linuxmi.com/java-enum.html
相关文章