Java枚举
来源:互联网 发布:php支付系统源码 2016 编辑:程序博客网 时间:2024/05/21 20:25
枚举比较简单用一个Demo来学习:
枚举类型定义:
package com.google.www.javacore.enumtest;/** * Created by dell on 2016/12/10. */public enum Size{ /** * 小号 */ SMALL("S"), /** *中号 */ MEDIUM("M"), /** * 大号 */ LARGE("L"), /** * 超大号 */ EXTRA_LARGE("EL"); Size(String name) { this.name = name; } String name; public String getName() { return name; }}
枚举类型的使用举例:
package com.google.www.javacore.enumtest;import java.util.Scanner;/** * Created by dell on 2016/12/10. */public class EnumDemo{ public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Enter a SIZE: "); String input = in.next().toUpperCase(); //valueof方法返回该枚举类型的对应常量值,若input非法直接抛出异常 Size s = (Size) Enum.valueOf(Size.class, input); //toString方法直接返回该常量的字符串 System.out.println("Size = " + s); System.out.println("The name of " + s +" is " + s.getName()); //比较两个枚举值常量时直接用==来比较,不用equals方法来比较。 if (Size.LARGE == s) { System.out.println("The size is Large."); } }}
附Enum的valueof方法:
/** * Returns the enum constant of the specified enum type with the * specified name. The name must match exactly an identifier used * to declare an enum constant in this type. (Extraneous whitespace * characters are not permitted.) * * <p>Note that for a particular enum type {@code T}, the * implicitly declared {@code public static T valueOf(String)} * method on that enum may be used instead of this method to map * from a name to the corresponding enum constant. All the * constants of an enum type can be obtained by calling the * implicit {@code public static T[] values()} method of that * type. * * @param <T> The enum type whose constant is to be returned * @param enumType the {@code Class} object of the enum type from which * to return a constant * @param name the name of the constant to return * @return the enum constant of the specified enum type with the * specified name * @throws IllegalArgumentException if the specified enum type has * no constant with the specified name, or the specified * class object does not represent an enum type * @throws NullPointerException if {@code enumType} or {@code name} * is null * @since 1.5 */ public static <T extends Enum<T>> T valueOf(Class<T> enumType, String name) { T result = enumType.enumConstantDirectory().get(name); if (result != null) return result; if (name == null) throw new NullPointerException("Name is null"); throw new IllegalArgumentException( "No enum constant " + enumType.getCanonicalName() + "." + name); }
0 0
- JAVA 枚举
- java枚举
- java枚举
- Java 枚举
- Java 枚举
- Java 枚举
- java 枚举
- java 枚举
- java枚举
- java枚举
- java枚举
- java枚举
- Java枚举
- java枚举
- java 枚举
- java枚举
- Java枚举
- Java枚举
- cookie实现购物车与session的登录判断
- 初中OJ1574. 【提高】X-因子链
- 纪中2016.12.10比赛总结
- 关于Android Handler机制的封
- CCS6.0的代码自动提示
- Java枚举
- 2016最新整理的Android面试题
- 人脸特征点检测:VanillaCNN
- C++使窗口全屏/最小化
- Idea SpringMVC项目读取.properties文件
- C语言 指针的细枝末节
- 260.数数小木块
- Qt示例[Image Viewer Example]
- December 10th 模拟赛C T4 二叉树 Solution