枚举类型

1.基本函数

枚举类型的基本函数如下:
public enum Weekday {
	MON,
	TUE,
	WED,
	THU,
	FRI,
	SAT,
	SUN
}
		for(Weekday weekday : Weekday.values()){
			System.out.print(weekday.ordinal() + " ");
			System.out.print(weekday.name() + " ");
			System.out.print(weekday.compareTo(Weekday.MON) + " ");
			System.out.print(weekday.equals(Weekday.MON) + " ");
			System.out.print(weekday.toString() + " ");
			System.out.print(weekday.getDeclaringClass() + " ");
			System.out.print(weekday.getClass() + " ");
			System.out.println();
			System.out.println("*************************************");
		}
输出如下:
0 MON 0 true MON class cn.com.codog.testenum.Weekday class cn.com.codog.testenum.Weekday 
*************************************
1 TUE 1 false TUE class cn.com.codog.testenum.Weekday class cn.com.codog.testenum.Weekday 
*************************************
2 WED 2 false WED class cn.com.codog.testenum.Weekday class cn.com.codog.testenum.Weekday 
*************************************
3 THU 3 false THU class cn.com.codog.testenum.Weekday class cn.com.codog.testenum.Weekday 
*************************************
4 FRI 4 false FRI class cn.com.codog.testenum.Weekday class cn.com.codog.testenum.Weekday 
*************************************
5 SAT 5 false SAT class cn.com.codog.testenum.Weekday class cn.com.codog.testenum.Weekday 
*************************************
6 SUN 6 false SUN class cn.com.codog.testenum.Weekday class cn.com.codog.testenum.Weekday 
*************************************

2.给Enum增加方法

enum也像普通的类一样可以添加方法,使得enum更具体化:
public enum Weekday {
	MON("尼玛,上班了"),
	TUE("又上了一天班"),
	WED("还有二天放假了"),
	THU("今天周几来着"),
	FRI("明天放假了"),
	SAT("还得加班"),
	SUN("哎呀,怎么还是六点起");
	private String desc;
	
	private Weekday(String desc){
		this.desc = desc;
	}

	public String getDesc() {
		return desc;
	}
	
	@Override
	public String toString() {
		return name() + ":" + getDesc();
	}
}
输出如下:
尼玛,上班了 MON:尼玛,上班了
******************
又上了一天班 TUE:又上了一天班
******************
还有二天放假了 WED:还有二天放假了
******************
今天周几来着 THU:今天周几来着
******************
明天放假了 FRI:明天放假了
******************
还得加班 SAT:还得加班
******************
哎呀,怎么还是六点起 SUN:哎呀,怎么还是六点起
******************

3.enum与switch一起使用


		Weekday weekday = Weekday.FRI;
		switch(weekday){
			case MON:
			case TUE:
			case WED:
			case THU:
			case FRI:	
				System.out.println("工作日");
				break;
			default:System.out.println("非工作日");	
		}
输出如下:
工作日

4.Enum类



Enum的代码如下:
/*
 * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 */

package java.lang;

import java.io.Serializable;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.ObjectStreamException;

/**
 * This is the common base class of all Java language enumeration types.
 *
 * More information about enums, including descriptions of the
 * implicitly declared methods synthesized by the compiler, can be
 * found in section 8.9 of
 * The Java™ Language Specification.
 *
 * 

Note that when using an enumeration type as the type of a set * or as the type of the keys in a map, specialized and efficient * {@linkplain java.util.EnumSet set} and {@linkplain * java.util.EnumMap map} implementations are available. * * @param The enum type subclass * @author Josh Bloch * @author Neal Gafter * @see Class#getEnumConstants() * @see java.util.EnumSet * @see java.util.EnumMap * @since 1.5 */ public abstract class Enum> implements Comparable, Serializable { /** * The name of this enum constant, as declared in the enum declaration. * Most programmers should use the {@link #toString} method rather than * accessing this field. */ private final String name; /** * Returns the name of this enum constant, exactly as declared in its * enum declaration. * * Most programmers should use the {@link #toString} method in * preference to this one, as the toString method may return * a more user-friendly name. This method is designed primarily for * use in specialized situations where correctness depends on getting the * exact name, which will not vary from release to release. * * @return the name of this enum constant */ public final String name() { return name; } /** * The ordinal of this enumeration constant (its position * in the enum declaration, where the initial constant is assigned * an ordinal of zero). * * Most programmers will have no use for this field. It is designed * for use by sophisticated enum-based data structures, such as * {@link java.util.EnumSet} and {@link java.util.EnumMap}. */ private final int ordinal; /** * Returns the ordinal of this enumeration constant (its position * in its enum declaration, where the initial constant is assigned * an ordinal of zero). * * Most programmers will have no use for this method. It is * designed for use by sophisticated enum-based data structures, such * as {@link java.util.EnumSet} and {@link java.util.EnumMap}. * * @return the ordinal of this enumeration constant */ public final int ordinal() { return ordinal; } /** * Sole constructor. Programmers cannot invoke this constructor. * It is for use by code emitted by the compiler in response to * enum type declarations. * * @param name - The name of this enum constant, which is the identifier * used to declare it. * @param ordinal - The ordinal of this enumeration constant (its position * in the enum declaration, where the initial constant is assigned * an ordinal of zero). */ protected Enum(String name, int ordinal) { this.name = name; this.ordinal = ordinal; } /** * Returns the name of this enum constant, as contained in the * declaration. This method may be overridden, though it typically * isn't necessary or desirable. An enum type should override this * method when a more "programmer-friendly" string form exists. * * @return the name of this enum constant */ public String toString() { return name; } /** * Returns true if the specified object is equal to this * enum constant. * * @param other the object to be compared for equality with this object. * @return true if the specified object is equal to this * enum constant. */ public final boolean equals(Object other) { return this==other; } /** * Returns a hash code for this enum constant. * * @return a hash code for this enum constant. */ public final int hashCode() { return super.hashCode(); } /** * Throws CloneNotSupportedException. This guarantees that enums * are never cloned, which is necessary to preserve their "singleton" * status. * * @return (never returns) */ protected final Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); } /** * Compares this enum with the specified object for order. Returns a * negative integer, zero, or a positive integer as this object is less * than, equal to, or greater than the specified object. * * Enum constants are only comparable to other enum constants of the * same enum type. The natural order implemented by this * method is the order in which the constants are declared. */ public final int compareTo(E o) { Enum other = (Enum)o; Enum self = this; if (self.getClass() != other.getClass() &&&& // optimization self.getDeclaringClass() != other.getDeclaringClass()) throw new ClassCastException(); return self.ordinal - other.ordinal; } /** * Returns the Class object corresponding to this enum constant's * enum type. Two enum constants e1 and e2 are of the * same enum type if and only if * e1.getDeclaringClass() == e2.getDeclaringClass(). * (The value returned by this method may differ from the one returned * by the {@link Object#getClass} method for enum constants with * constant-specific class bodies.) * * @return the Class object corresponding to this enum constant's * enum type */ @SuppressWarnings("unchecked") public final Class getDeclaringClass() { Class clazz = getClass(); Class zuper = clazz.getSuperclass(); return (zuper == Enum.class) ? (Class)clazz : (Class)zuper; } /** * 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.) * *

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 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 valueOf(Class 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); } /** * enum classes cannot have finalize methods. */ protected final void finalize() { } /** * prevent default deserialization */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { throw new InvalidObjectException("can't deserialize enum"); } private void readObjectNoData() throws ObjectStreamException { throw new InvalidObjectException("can't deserialize enum"); } }

发现这个Enum类并没有values方法,但是客户端程序员可以调用values方法,《java编程思想》说的是编译器添加的values方法,这个就当长姿势就行了,感觉没必要深究。

5.EnumSet

enum能满足绝大部分情况了,但是不能够修改,enumSet可以根据现有的enum实现自己的需求,代码如下:
		EnumSet weekdays = EnumSet.noneOf(Weekday.class);
		System.out.println(weekdays);
		weekdays.add(Weekday.MON);
		System.out.println(weekdays);
		weekdays.addAll(EnumSet.range(Weekday.TUE, Weekday.SUN));
		System.out.println(weekdays);
		weekdays.remove(Weekday.MON);
		System.out.println(weekdays);
		weekdays = EnumSet.complementOf(weekdays);
		System.out.println(weekdays);

6.EnumMap


EnumMap操作类似于普通的Map,但是key必须是Enum对象,代码如下:
		EnumMap commands = new EnumMap<>(Weekday.class);
		commands.put(Weekday.MON, () -> {System.out.println("尼玛,又上班了");});
		commands.put(Weekday.TUE, () -> {System.out.println("又上了一天班");});
		for(Entry command : commands.entrySet()){
			System.out.println(command.getKey() + " : " + command.getValue());
		}
输出如下:
MON:尼玛,上班了 : cn.com.codog.testenum.TestWeekday$$Lambda$1/471910020@816f27d
TUE:又上了一天班 : cn.com.codog.testenum.TestWeekday$$Lambda$2/303563356@87aac27

7.Enum实例


大部分情况下可以将Enum里面的实例看作是Enum的子类来看,比如覆盖Enum类中定义的方法:
public enum Weekday {
	MON("尼玛,上班了") {
		@Override
		void printInfo() {
			System.out.println("MON");
		}
	},
	TUE("又上了一天班") {
		@Override
		void printInfo() {
			System.out.println("TUE");
		}
	},
	WED("还有二天放假了") {
		@Override
		void printInfo() {
			System.out.println("WED");
		}
	},
	THU("今天周几来着") {
		@Override
		void printInfo() {
			System.out.println("THU");
		}
	},
	FRI("明天放假了") {
		@Override
		void printInfo() {
			System.out.println("FRI");
		}
	},
	SAT("还得加班") {
		@Override
		void printInfo() {
			System.out.println("SAT");
		}
	},
	SUN("哎呀,怎么还是六点起") {
		@Override
		void printInfo() {
			System.out.println("SUN");
		}
	};
	private String desc;

	private Weekday(String desc) {
		this.desc = desc;
	}

	public String getDesc() {
		return desc;
	}

	abstract void printInfo();

	@Override
	public String toString() {
		return name() + ":" + getDesc();
	}
}

8.利用enum实现职责链模式


代码如下:
public enum Weekday {
	MON("尼玛,上班了") {
		@Override
		boolean printInfo(String str) {
			//System.out.println("MON");
			return str.startsWith("MON");
		}
	},
	TUE("又上了一天班") {
		@Override
		boolean printInfo(String str) {
			//System.out.println("TUE");
			return str.startsWith("TUE");
		}
	},
	WED("还有二天放假了") {
		@Override
		boolean printInfo(String str) {
			//System.out.println("WED");
			return str.startsWith("WED");
		}
	},
	THU("今天周几来着") {
		@Override
		boolean printInfo(String str) {
			//System.out.println("THU");
			return str.startsWith("THU");
		}
	},
	FRI("明天放假了") {
		@Override
		boolean printInfo(String str) {
			//System.out.println("FRI");
			return str.startsWith("FRI");
		}
	},
	SAT("还得加班") {
		@Override
		boolean printInfo(String str) {
			//System.out.println("SAT");
			return str.startsWith("SAT");
		}
	},
	SUN("哎呀,怎么还是六点起") {
		@Override
		boolean printInfo(String str) {
			//System.out.println("SUN");
			return str.startsWith("SUN");
		}
	};
	private String desc;

	private Weekday(String desc) {
		this.desc = desc;
	}

	public String getDesc() {
		return desc;
	}

	abstract boolean printInfo(String str);

	@Override
	public String toString() {
		return name() + ":" + getDesc();
	}
}
		String startWorkday = "FRI";
		for(Weekday weekday : Weekday.values()){
			if(weekday.printInfo(startWorkday)){
				System.out.println(weekday.getDesc());
				break;
			}
		}
输出如下:
明天放假了

相关内容:
前言
对象和类型
操作符和引用
流程控制语句
初始化和清理
访问控制
组合和继承
接口和多态
接口与抽象类
容器
异常
类型信息
泛型
数组
IO系统
枚举类型
注解
多线程
总结