1

How can i pre-define any types of values in the Enum?

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 Answers 3

5

You can define members in enums. Then override the toString()

You can define a getDesc() method which is IMO better that override 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;
    }
}

Just note that is solution is available starting at Java version 1.5

Sign up to request clarification or add additional context in comments.

Comments

2
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;
    }
}

1 Comment

Thanks, i dont wanted to make external files. So this worked.
0
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;
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.