Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple Integer Enum

Tags:

java

enums

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

like image 490
mastaH Avatar asked Jul 20 '11 13:07

mastaH


People also ask

Can we use integer in enum?

No, we can have only strings as elements in an enumeration.

What is enum with example?

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.

Is enum always integer?

Enumerations are integers, except when they're not - Embedded.com.


2 Answers

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
    }
}
like image 175
Bohemian Avatar answered Sep 24 '22 19:09

Bohemian


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.

like image 44
Jeffrey Avatar answered Sep 23 '22 19:09

Jeffrey