论坛首页 Java企业应用论坛

【解惑】理解java枚举类型

浏览 36393 次
该帖已经被评为良好帖
作者 正文
   发表时间:2009-09-28  
补充一点:
EnumMap<K extends Enum<K>,V>和EnumSet<E extends Enum<E>>两个集合类型,都是专门针对枚举类型。

EnumMap<Color, String> map = new EnumMap<Color, String>(Color.class);
		map.put(Color.RED, "red");
		map.put(Color.BLUE,"blue");
		
		for(Color c: Color.values()){
			System.out.println(map.get(c));
		}
1 请登录后投票
   发表时间:2009-09-28   最后修改:2009-09-28
很棒的帖子。enum用得很少。这次子清楚多了
0 请登录后投票
   发表时间:2009-09-29  
以前没有用过enum,看来挺好用,准备试试
0 请登录后投票
   发表时间:2009-11-13  
一般吧,关于Enum的相关知识,在《java编程思想》这本书中有详细的介绍!
0 请登录后投票
   发表时间:2009-11-19  
讲解的相当棒~谢谢~
0 请登录后投票
   发表时间:2010-05-12   最后修改:2010-05-12
利用多态更是暴力啊,呵呵。
本人写了个《Java面向对象设计最佳实践 - 枚举设计》
http://www.iteye.com/topic/664600,欢迎交流学习
0 请登录后投票
   发表时间:2010-08-04  
楼主,
如果我再 :   private int redValue;  //自定义数据域,private为了封装。  
                private int greenValue;  
                private int blueValue;  

添加以上三个属性的get方法,然后将其放到一个类中如:
public class MyEnumTest{
//此处添加进你的Enum Color ,当然要添加里面的三个属性get()

private Color color;
//其get和set方法省。。


public MyEnumTest() {}

public MyEnumTest(Color color ) {
this.color = color ;
}

public static void main(String[] args) {
//在此我想打印getRedValue()的值

//此处却是 空???
}
}

那么怎么处理?
0 请登录后投票
   发表时间:2010-08-04  
ihopethatwell 写道

完全没问题
public class BeanWithEnumAttribute {
	private Color color;
	public BeanWithEnumAttribute(Color color) {
		this.color = color;
	}
	@Override
	public String toString() {
		return "BeanWithEnumAttribute(" + color.getRedValue() + "," + color.getGreenValue() + "," + color.getBlueValue() + ")";
	}
	public static void main(String[] args) {
		BeanWithEnumAttribute bean = new BeanWithEnumAttribute(Color.BLUE);
		System.out.println(bean);
	}
}

输出
引用
BeanWithEnumAttribute(0,0,255)
0 请登录后投票
   发表时间:2010-08-10  
非常感谢楼主的这篇文章,让我有一种茅塞盾开的感觉.以前枚举用得也不多,一直很迷糊!学习了!
0 请登录后投票
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics