package cn.com.myenum;
public enum Fruit{
orange("桔子",0),apple("蘋果",1);
private String name;
private int index;
private Fruit(String name,int index){
this.index=index;
this.name=name;
}
public static String getName(int index){
for(Fruit f:Fruit.values()){
if(f.getIndex()==index){
return f.name;
}
}
return null;
}
public static int getIndex(String name){
for(Fruit f:Fruit.values()){
if(f.getName().equals(name)){
return f.index;
}
}
return -1;
}
public String getName(){
return name;
}
public void setName(String name){
this.name=name;
}
public int getIndex(){
return index;
}
public void setIndex(int index){
this.index=index;
}
}
package cn.com.myenum;
public class FruitTest {
public static void main(String[] args) {
System.out.println(Fruit.orange.getName());
System.out.println(Fruit.orange.getIndex());
System.out.println(Fruit.getIndex("桔子"));
System.out.println(Fruit.getName(1));
}
}
本文版權歸傳智播客Java培訓學院所有,歡迎轉載,轉載請注明作者出處。謝謝!
作者:傳智播客Java培訓學院
首發(fā):http://xamj520.com/javaee