Simple Integer Enum

I am new to enums, and I would like to create it to compare an integer with a more understandable definition.

if (getFruit() == myEnum.APPLE) {
    // ...
}

instead

if (getFruit() == 1) {
    // ...
}

Where getFruit()returns values ​​such as 1, 2etc.

+5
source share
4 answers

You don't have enough enumeration points ... you use them instead of the "old school" constants int.

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
    }
}
+8
source

You can use getFruit() == myEnum.APPLE.ordinal()where serial number is the order in which you declare enumerations 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 can 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;
    }
}

getFruit() .

+4

,

public enum myEnum {
    APPLE  (1),
    ORANGE (2);
}

tutorial

+2
source
public enum Fruit {
    APPLE  ("apple"), ORANGE ("orange");

    private String value;

    private Fruit(int v) { value = v; }
}

getFruit should return a listing of fruits

public Fruit getFruit() {
    return aFruit;
}

Now you can use

if (getFruit() == Fruit.APPLE) { //and so on
    // ...
}

And if you use an enumeration, it is better to use a switching case

switch(getFruit()) {
    case Fruit.APPLE: ... break;
    case Fruit.ORANGE: ... break;
}
+1
source

All Articles