枚举比较简单用一个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);
}