tags:

views:

70

answers:

4

I want to accomplish something like the following (my interest is in the toInt() method). Is there any native way to accomplish this? If not, how can I get the integer associated with an enum value (like in C#) ?

enum Rate {
 VeryBad(1),
 Bad(2),
 Average(3),
 Good(4),
 Excellent(5);

 private int rate;

 private Rate(int rate) {
  this.rate = rate;
 }

 public int toInt() {
  return rate;
 }
}

Thanks

A: 

Java enums are not like C# enums. They are objects as opposed to just a name for an integer constant. The best you could do is look at the hash code for the objects, but that will not give you any real meaningful/ useful information in the sense I believe you are looking for. The only real way to do it is as in your example code assigning a property to the enum and a means for accessing it (either via a method, or as a public final field).

M. Jessup
But how to implement that method? My toInt() as far as I can tell won't work in java. I don't have a way to call it.
devoured elysium
You call it on the enum value itself: Rate.Excellent.toInt(), or if you were to make the field rate public (and in good style final as well) you could say Rate.Excellent.rate.
M. Jessup
A: 
return enumVal.ordinal();

(see the javadoc)

Edit: I originally misread your code; you seem to be doing all the int/enum conversion stuff manually, when Java handles all that. You really shouldn't need to use ints, you can just use the enums as a separate type. As the javadoc says, it's unlikely you'll ever actually want the int associated with a particular value; "Good" and "4" don't have any connection to each other, 4 just happens to be its position in the enum

Michael Mrozek
If I have a set of objects with rating, I'll want to know what is the average rate. So manipulating them as integers is not only an advantage, it's a necessity.
devoured elysium
A: 

Not sure if this answers your question but an enum instance has an ordinal() method returning its position as an int. But it is bad practice to rely on it, the instance field as shown in your example is the way to go...

pgras
+2  A: 

In "Effective Java" Joshua Bloch recommends the following pattern:

private static final Map<Integer, Rate> intToEnum = new HashMap<Integer, Rate>();
static
{
   for(Rate rate: values())
      intToEnum.put(Integer.valueOf(rate.toInt()), rate);
}
public static Rate fromInt(int intVal)
{
   return intToEnum.get(Integer.valueOf(intVal));
}
Dominik
He also suggests avoiding `ordinal()`, as "Most programmers will have no use for this method." http://java.sun.com/javase/6/docs/api/java/lang/Enum.html#ordinal%28%29
trashgod
to place inside enum, great thing!
Aleksey Otrubennikov