How can i pre-define any t开发者_如何学Goypes 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
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
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;
}
}
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;
}
}
精彩评论