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培训学院
首发:http://www.itcast.cn/javaee