java枚举的使用

package com.emenu.common.enums.party;

import java.util.HashMap;
import java.util.Map;

/**
 * AccountTypeEnums
 * @time: 15/10/16 上午9:32
 */
public enum AccountTypeEnums {

    Normal(1, "正常账户"),
Wechat(2, "微信账户");

    private Integer id;
    private String type;

/*构造函数,初始化变量*/
AccountTypeEnums(Integer id, String type) {
        this.id = id;
        this.type = type;
}

    /*static:方便在没有创建对象的情况下调用(方法或变量),不需实例化对象,直接用(类名.成元变量/成员函数)*/
    /*hashmap:数组+链表结构,数组存第一地址,链表上挂第一地址相同的值,找到第一地址再遍历其上的链表*/
private static Map<Integer, AccountTypeEnums> map = new HashMap<Integer, AccountTypeEnums>();

/*foreach:  语句格式:
     for(元素类型t 元素变量x : 遍历对象obj){
引用了xjava语句;
     }
     */
    /*定义put(K key,V value)等函数,关联指定的KeyValue,并加入到链表中 */
static {
        for (AccountTypeEnums enums : AccountTypeEnums.values()) {
            map.put(enums.getId(), enums); //直接调用成员函数.
}
    }

    /*根据id取出枚举中对应的值*/
public static AccountTypeEnums valueOf(int id) {
        return valueOf(id, null);
}

    /*定义get(K key)等函数,通过指定键获取对应的Value*/
public static AccountTypeEnums valueOf(int id, AccountTypeEnums defaultValue) {
        AccountTypeEnums enums = map.get(id);
        return enums == null ? defaultValue : enums;
}

    public Integer getId() {
        return id;
}

    public String getType() {
        return type;
}
}

猜你喜欢

转载自2514313567.iteye.com/blog/2320286