Enum练习
1. 不带参数的Enum
创建Enum
public enum fruitEnum {
APPLE,PEAR,BANANA,ORANGE;
}
测试Enum
public static void testFruitEnum(){
for(fruitEnum fruit:fruitEnum.values()){
System.out.println(fruit+",ordinal:"+fruit.ordinal()+",name:"+fruit.name());
}
}
测试结果
APPLE,ordinal:0,name:APPLE
PEAR,ordinal:1,name:PEAR
BANANA,ordinal:2,name:BANANA
ORANGE,ordinal:3,name:ORANGE
Process finished with exit code 0
2. 带一个参数的Enum
创建Enum
public enum fruitEnum2 {
APPLE("red"), BANANA("yellow"), ORANGE("orange"), PEAR("green");
private final String color;
fruitEnum2(String color) {
this.color=color;
}
public String getColor(){
return this.color;
}
public static fruitEnum2 getFruitByColor(String color){
for(fruitEnum2 fruit:fruitEnum2.values()){
if(fruit.getColor().equals(color)){
return fruit;
}
}
return null;
}
}
测试Enum
/* test fruitEnum2
*/
public static void testFruitEnum2(){
fruitEnum2 fruit = fruitEnum2.getFruitByColor("yellow");
assert fruit != null;
System.out.println(fruit+",color:"+fruit.getColor()+",ordinal:"+fruit.ordinal()+",name:"+fruit.name());
}
public static void main(String[] args){
testFruitEnum2();
}
测试结果
BANANA,color:yellow,ordinal:1,name:BANANA
Process finished with exit code 0
3. 带两个参数的Enum
创建Enum
public enum fruitEnum3 {
APPLE("red","happy"), BANANA("yellow","vitality"), ORANGE("orange","warm"), PEAR("green","calm");
private String color;
private String feeling;
fruitEnum3(String color,String feeling) {
this.color=color;
this.feeling=feeling;
}
public String getColor(){
return this.color;
}
public void setColor(String color){
this.color=color;
}
public String getFeeling(){
return this.feeling;
}
public void setFeeling(String feeling){
this.feeling=feeling;
}
public static fruitEnum3 getFruitByColor(String color){
for(fruitEnum3 fruit: fruitEnum3.values()){
if(fruit.getColor().equals(color)){
return fruit;
}
}
return null;
}
public static fruitEnum3 getFruitByFeeling(String feeling){
for(fruitEnum3 fruit: fruitEnum3.values()){
if(fruit.getFeeling().equals(feeling)){
return fruit;
}
}
return null;
}
}
测试Enum
/* test fruitEnum3
*/
public static void testFruitEnum3(){
// fruitEnum3 fruit = fruitEnum3.getFruitByColor("yellow");
fruitEnum3 fruit = fruitEnum3.getFruitByFeeling("warm");
if (fruit != null) {
System.out.println(fruit+",color:"+fruit.getColor()+",ordinal:"+fruit.ordinal()+",name:"+fruit.name());
}
}
public static void main(String[] args){
testFruitEnum3();
}
测试结果
ORANGE,color:orange,ordinal:2,name:ORANGE
Process finished with exit code 0