Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum with int value in Java

Tags:

java

c#

enums

What's the Java equivalent of C#'s:

enum Foo {   Bar = 0,   Baz = 1,   Fii = 10, } 
like image 720
ripper234 Avatar asked Nov 05 '09 16:11

ripper234


People also ask

Can enum have int values?

The enum can be of any numeric data type such as byte, sbyte, short, ushort, int, uint, long, or ulong. However, an enum cannot be a string type.

Can enums be integers Java?

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

How do I add value to an enum in Java?

You cannot create an object of an enum explicitly so, you need to add a parameterized constructor to initialize the value(s). The initialization should be done only once. Therefore, the constructor must be declared private or default. To returns the values of the constants using an instance method(getter).


2 Answers

If you want attributes for your enum you need to define it like this:

public enum Foo {     BAR (0),     BAZ (1),     FII (10);      private final int index;         Foo(int index) {         this.index = index;     }      public int index() {          return index;      }  } 

You'd use it like this:

public static void main(String[] args) {     for (Foo f : Foo.values()) {        System.out.printf("%s has index %d%n", f, f.index());     } } 

The thing to realise is that enum is just a shortcut for creating a class, so you can add whatever attributes and methods you want to the class.

If you don't want to define any methods on your enum you could change the scope of the member variables and make them public, but that's not what they do in the example on the Sun website.

like image 112
Dave Webb Avatar answered Sep 20 '22 15:09

Dave Webb


If you have a contiguous range of values, and all you need is the integer value, you can just declare the enum minimally:

public enum NUMBERZ {         ZERO, ONE, TWO } 

and then obtain the int value as follows:

int numberOne = NUMBERZ.ONE.ordinal(); 

However, if you need a discontiguous range (as in your example, where you jump from 1 to 10) then you will need to write your own enum constructor which sets your own member variable, and provide a get method for that variable, as described in the other answers here.

like image 45
Carl Avatar answered Sep 18 '22 15:09

Carl