I'm new with enums
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
No, we can have only strings as elements in an enumeration.
An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.
Enumerations are integers, except when they're not - Embedded.com.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With