如何在Java中使用我的Enum设置整数,字符串值?

时间:2011-09-28 10:01:06

标签: java types enums

如何在枚举中预先定义任何类型的值?

public enum Hardware
{
    USB2(0) = "external low speed",
    PCI(1)  = "embedded",
    USB3(2) = "external high speed
}

System.out.println( Hardware.USB2 ) // show me external low speed

3 个答案:

答案 0 :(得分:6)

您可以在members中定义enums。然后覆盖toString()

您可以定义更好的IMO getDesc()方法来覆盖toString()

public enum Hardware
{
    USB2(0, "external low speed"),
    PCI(1,"embedded"),
    USB3(2,"external high speed");

    private String desc;
    private int id;

    private Hardware(int id, String desc) {
        this.id = id;
        this.desc = desc;
    }

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

请注意,解决方案可从Java版本1.5

开始提供

答案 1 :(得分:3)

enum Hardware
{
    USB2("external low speed"),
    PCI("embedded"),
    USB3("external high speed");

    private String val;

    private Hardware(String val){
        this.val = val;
    }

    public String toString(){
        return val;
    }
}

答案 2 :(得分:1)

public enum Hardware {
    USB2(0, "external low speed"),
    PCI(1,"embedded"),
    USB3(2,"external high speed);

    String desc;
    int id;

    public Hardware(int id, String desc) {
        this.id = id;
        this.desc = desc;
    }

    public String toString() {
        return this.desc;
    }
}