枚举的应用

来源:互联网 发布:smo算法 python 编辑:程序博客网 时间:2024/05/19 17:06
Properties pro = new Properties();
try {
    InputStream inStr = ClassLoader.getSystemResourceAsStream("wahaha.properties");
    pro.load(inStr);
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}


//propertyNames(),返回属性列表中所有键的枚举
Enumeration enu2=pro.propertyNames();
while(enu2.hasMoreElements()){
    String key = (String)enu2.nextElement();
    System.out.println(key);
}


//Properties 继承于 Hashtable,elements()是Hashtable的方法,返回哈希表中的值的枚举。
Enumeration enu=pro.elements();
while(enu.hasMoreElements()){
    String key = (String)enu.nextElement();
    System.out.println(key);
}


//Properties 继承于 Hashtable,entrySet()是Hashtable的方法,
//返回此 Hashtable 中所包含的键的 Set 视图。此 collection 中每个元素都是一个 Map.Entry
Iterator it=pro.entrySet().iterator();
while(it.hasNext()){
    Map.Entry entry=(Map.Entry)it.next();
    Object key = entry.getKey();
    Object value = entry.getValue();
    System.out.println(key +":"+value);
}










1、    目的
        简单认为:满足一些需求
2、    定义、使用
public enum SexEnum {
    male(1),female(0);
   
    private final int value;
   
    private SexEnum(int value){
        this.value = value;
    }
   
    public int getValue(){
        return this.value;
    }
}


public class TestSexEnum {
    /*
     * @param args
     */
    public static void main(String[] args) {
        System.out.println(SexEnum.male.getValue());
        for (SexEnum item:SexEnum.values()){
            System.out.println(item.toString()+item.getValue());
        }


    }


}
3、与类/接口相比
=与类相同,不同的地方就是写法不一样(enum比较简单,但是写法比较陌生)
=同样可以添加方法,属性
=enum不能继承类(包括继承enum),只能实现接口,类无此限制(除非用final来限制)。在这个方面,enum更像interface
=enum只支持public和[default] 访问修饰,class支持比较丰富
=可以与下面的类比较一下,定义比较相似
Public class Sex{
    Public static final Sex male = new Sex(1);
    Public static final Sex female = new Sex(0);


    Private Sex(int value){
        This.value = value;
}


Public int getValue(){
    Return this.value;
}
}


=调用比较相似
SexEnum.male.getValue()
Sex.male.getValue()


        总结:其实完全能够用class替代enum,个人认为enum是早期面向过程中,简单数值枚举集合的一种表示,在java中对enum进行了扩展,让它只具有类的部分能力,导致结构不清晰,在java中进入enum有画蛇添足的感觉.
原创粉丝点击