如何在枚举中预先定义任何类型的值?
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
答案 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;
}
}