当前位置:首页 > 开发 > 编程语言 > Java > 正文

JAVA 枚举的简单应用

发表于: 2011-11-22   作者:chenzenghua   来源:转载   浏览:
摘要: public class Test { public static void main(String[] args) { for (Education e : Education.values()) { System.out.println("Name : " + e.getName() + " | Value : " +
public class Test {
	public static void main(String[] args) {
		for (Education e : Education.values()) {
			System.out.println("Name : " + e.getName() + " | Value : "
					+ e.getValue());
		}
		System.out.println(Education.Shuoshi.getName());
		System.out.println(Education.Benke.getValue());
		System.out.println("=================================================");
		double x = 5;
		double y = 10;
		for (Operation op : Operation.values()) {
			System.out.println(x + op.toString() + y + " = " + op.apply(x, y));
		}
	}
}

enum Education {
	Boshi("博士", 1), Shuoshi("硕士", 2), Benke("本科", 3), Gaozhong("高中", 4);
	private String name;
	private int value;

	private Education(String name, int value) {
		this.name = name;
		this.value = value;
	}

	public String getName() {
		return this.name;
	}

	public int getValue() {
		return this.value;
	}
}

enum Operation {
	PLUS("+") {
		@Override
		double apply(double x, double y) {
			return x + y;
		}
	},
	MINUS("-") {
		@Override
		double apply(double x, double y) {
			return x - y;
		}
	},
	TIMES("*") {
		@Override
		double apply(double x, double y) {
			return x * y;
		}
	},
	DIVIDE("/") {
		@Override
		double apply(double x, double y) {
			return x / y;
		}
	};
	private String symbol;

	private Operation(String symbol) {
		this.symbol = symbol;
	}

	abstract double apply(double x, double y);

	@Override
	public String toString() {
		return this.symbol;
	}
}

输出结果:
Name : 博士 | Value : 1
Name : 硕士 | Value : 2
Name : 本科 | Value : 3
Name : 高中 | Value : 4
硕士
3
=================================================
5.0+10.0 = 15.0
5.0-10.0 = -5.0
5.0*10.0 = 50.0
5.0/10.0 = 0.5

利用枚举实现java单例:包含一个元素的枚举:
enum Singleton{
	INSTANCE;
	public void doSomething(){
		//...
	}
}

JAVA 枚举的简单应用

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号