Java枚举使用
2017-10-24 15:47
99 查看
在JDK1.5 之前,我们定义常量都是: public static fianl.... 。
现在好了,有了枚举,可以把相关的常量分组到一个枚举类型里,而且枚举提供了比常量更多的方法。
1、不用枚举
2、用枚举:改变上面
3、用枚举:多个参数
现在好了,有了枚举,可以把相关的常量分组到一个枚举类型里,而且枚举提供了比常量更多的方法。
1、不用枚举
package First; public class Test { public static final int RED = 1; public static final int Green = 3; public static final int YELLOW = 2; public static void main(String[] args) { int value = Test.Green; System.out.println(value); } }
2、用枚举:改变上面
package First; public class LightTest { public enum Light{ RED(1),Green(3),YELLOW(2); private int nCode; /* * 1. private类型的构造函数 * 2. 给变量赋值 */ private Light(int nCode){ this.nCode = nCode; } /* * 获取各个变量的值 */ public int getValue(){ return nCode; } } public static void main(String[] args) { Light light = Light.Green; int value = light.getValue(); System.out.println(value); System.out.println("----------------"); //遍历 Light[] lights = Light.values(); for(Light a : lights){ System.out.println(a); System.out.println(a.nCode); } } }
3、用枚举:多个参数
package First; public class LightTest { public enum Light{ RED(1,"红"),Green(3,"绿"),YELLOW(2,"黄"); private int nCode; private String str; /* * 1. private类型的构造函数 * 2. 给变量赋值 */ private Light(int nCode, String str){ this.nCode = nCode; this.str = str; } /* * 获取各个变量的值 */ public int getValue(){ return nCode; } public String getStr(){ return str; } } public static void main(String[] args) { Light light = Light.Green; int value = light.getValue(); String str = light.getStr(); System.out.println(value); System.out.println(str); } }
相关文章推荐
- java的枚举enum的简单使用
- java枚举使用详解
- java中枚举enum的使用
- Java枚举(用Java普通类模拟枚举的实现原理及JDK枚举API使用示例)
- java使用枚举
- Java枚举(用Java普通类模拟枚举的实现原理及JDK枚举API使用示例)
- Java枚举使用一例
- 01-java基础加强,eclipse工具使用,快捷键,断点调试,单元测试,jdk5新特性,增强for循环,集合map,list,可变参数,枚举,反射,泛型
- Java enum(枚举)的简单使用
- java 定义枚举+枚举使用
- java enum枚举的使用
- 再谈在Java中使用枚举
- 加强eclipse的使用技巧。可变参数。基本数据类型自动装箱和拆箱。枚举。反射。数组反射的应用。ArrayList和HashSet。JavaBean
- java枚举使用详解
- 高阶Java枚举类型enum使用详解
- java enum(枚举)使用详解 + 总结
- 高阶Java枚举类型enum使用详解
- Annotation & Enum :Java中注解和枚举的使用
- 再谈在Java中使用枚举
- java中Enum(枚举)的使用