Simple Integer Enum
I'm new with e开发者_运维技巧nums
and I'd like to create one to compare an integer to a more comprehensible definition.
if (getFruit() == myEnum.APPLE) {
// ...
}
instead of
if (getFruit() == 1) {
// ...
}
Where getFruit()
returns values like 1
,2
and so on
You are missing the point of enums... you use them instead of "old school" int
constants.
Have a look at this:
public enum Fruit {
APPLE,
ORANGE,
BANANA
}
public class Dessert {
private Fruit fruit;
public Dessert(Fruit fruit) {
this.fruit = fruit;
}
public Fruit getFruit() {
return fruit;
}
}
public class Test {
Dessert dessert = new Dessert(Fruit.APPLE);
if (dessert.getFruit() == Fruit.ORANGE) {
// nope
} else if (dessert.getFruit() == Fruit.APPLE) {
// yep
}
}
You can use getFruit() == myEnum.APPLE.ordinal()
where ordinal is the order you declare the enums in your file.
public enum myEnum {
APPLE, ORANGE, BANANA;
}
The ordinal for APPLE in this case is 0, ORANGE is 1, BANANA is 2.
Or you could do the following:
public enum myEnum {
APPLE(1), ORANGE(2), BANANA(3);
private final int i;
private myEnum(int i){
this.i=i;
}
public int getNumber(){
return i;
}
}
However, I would just make getFruit()
return an enum.
You can create an enum like this
public enum myEnum {
APPLE (1),
ORANGE (2);
}
You can also check this tutorial
public enum Fruit {
APPLE ("apple"), ORANGE ("orange");
private String value;
private Fruit(int v) { value = v; }
}
getFruit must return Fruit enum
public Fruit getFruit() {
return aFruit;
}
Now you can use
if (getFruit() == Fruit.APPLE) { //and so on
// ...
}
And if you use enum, its better to use switch-case
switch(getFruit()) {
case Fruit.APPLE: ... break;
case Fruit.ORANGE: ... break;
}
精彩评论