How do I convert an int to an enum?

Q

qu0ll

I have built a simple enum class for storing various known int return values
from a particular method. It looks like this:

public enum ReturnValue
{
POSITIVE(0),
NEGATIVE(1),
EITHER(2),
UNDEFINED(3);

private int value;

public int value()
{
return value;
}

ReturnValue(int value)
{
this.value = value;
}
}

Now I face the issue of how to convert the int return value from the method
into one of these enum values. My solution was to add this method to the
enum class:

public static ReturnValue convert(int value)
{
switch (value)
{
case 0:
return POSITIVE;
case 1:
return NEGATIVE;
case 2:
return EITHER;
case 3:
return UNDEFINED;
default:
return UNDEFINED;
}

Is this the way to do it? Now to convert all I do is:

ReturnValue x = ReturnValue.convert(method());

But this seems silly to have to define the int values of each enum value
effectively twice. Is there a better (simpler) way?

--
And loving it,

qu0ll
______________________________________________
(e-mail address removed)
(Replace the "SixFour" with numbers to email)
 
H

Hendrik Maryns

qu0ll schreef:
I have built a simple enum class for storing various known int return values
from a particular method. It looks like this:
{
switch (value)
{
case 0:
return POSITIVE;
case 1:
return NEGATIVE;
case 2:
return EITHER;
case 3:
return UNDEFINED;
default:
return UNDEFINED;
}

Is this the way to do it? Now to convert all I do is:

No. The moment you need the numbers behind enums, you are not using
them correctly.
ReturnValue x = ReturnValue.convert(method());

But this seems silly to have to define the int values of each enum value
effectively twice. Is there a better (simpler) way?

Why doesn’t your method() return a ReturnValue?

H.
--
Hendrik Maryns
http://tcl.sfs.uni-tuebingen.de/~hendrik/
==================
http://aouw.org
Ask smart questions, get good answers:
http://www.catb.org/~esr/faqs/smart-questions.html
 
Q

qu0ll

Hendrik Maryns said:
qu0ll schreef:


No. The moment you need the numbers behind enums, you are not using them
correctly.


Why doesn't your method() return a ReturnValue?

Because it's not my method and it returns an int. I thought it would be
nice to process the value and pass it around the application as an enum
instead. Are you saying that it's not possible to convert?

--
And loving it,

qu0ll
______________________________________________
(e-mail address removed)
(Replace the "SixFour" with numbers to email)
 
C

Chris Brat

Hi,

I've also used this approach.

The scenario is that a field in my database stores an int value that
corresponds to a particular enum item. Instead of working with the int
value, I rather use the enum - this gives extra parameter safety to my
methods, because only one of the predefined enum entries is allowed.
Its also more readable to me.

Hendrik, why is this an incorrect way to use enums?

Regards,
Chris
 
Q

qu0ll

Chris Brat said:
Hi,

I've also used this approach.

The scenario is that a field in my database stores an int value that
corresponds to a particular enum item. Instead of working with the int
value, I rather use the enum - this gives extra parameter safety to my
methods, because only one of the predefined enum entries is allowed.
Its also more readable to me.

Hendrik, why is this an incorrect way to use enums?

Regards,
Chris

Yes, this is the same situation for me. The method() returns a value from
the database that I want to manipulate as an enum. Is it possible?

--
And loving it,

qu0ll
______________________________________________
(e-mail address removed)
(Replace the "SixFour" with numbers to email)
 
H

Hendrik Maryns

Chris Brat schreef:
Hi,

I've also used this approach.

The scenario is that a field in my database stores an int value that
corresponds to a particular enum item. Instead of working with the int
value, I rather use the enum - this gives extra parameter safety to my
methods, because only one of the predefined enum entries is allowed.
Its also more readable to me.

Hendrik, why is this an incorrect way to use enums?

Well, stated this way, I think it is OK, because the database forces you
to use ints, so conversion is necessary. But a pure Java program using
Enums should have no need to have numbers associated with the enums.

(I mean numbers *enum*erating them, not stuff like in the planet mass
example at sun’s.)

H.
--
Hendrik Maryns
http://tcl.sfs.uni-tuebingen.de/~hendrik/
==================
http://aouw.org
Ask smart questions, get good answers:
http://www.catb.org/~esr/faqs/smart-questions.html
 
M

Michael Rauscher

qu0ll said:
Is this the way to do it? Now to convert all I do is:

ReturnValue x = ReturnValue.convert(method());

But this seems silly to have to define the int values of each enum value
effectively twice. Is there a better (simpler) way?

public static ReturnValue convert( int value ) {
ReturnValue result = null; // or: = ReturnValue.UNDEFINED
ReturnValue values[] = ReturnValue.values();
int i = 0;
while ( i < values.length && result == null )
if ( values.value == value )
result = values;
else
i++;

return result;
}

Bye
Michael
 
C

Chris Uppal

qu0ll said:
Because it's not my method and it returns an int. I thought it would be
nice to process the value and pass it around the application as an enum
instead. Are you saying that it's not possible to convert?

Unlike C and C++ Java's enums are /not/ a way to give more readable names to
integer values. They are objects (with -- like all objects -- their own
behaviour suited to whatever tasks they will be asked to perform). You should
make up your mind whether you want to work with integer values (as returned by
your original routine) or with objects.

If you want to work with integers, then just define "public static final int"
constants for the possible values, and use those names.

If you want to use objects to represent the return values (whether you use
Java's enum objects, or some other kind of object) then you'll have to have a
step somewhere where you write code to convert from one to the other. Note
that if you are using objects then it is not at all clear that they /have/ to
"know" what numerical return value they stand for (it may be useful, but I
don't see a really convincing need for it). The kinds of things they need to
know might include stuff like "do I represent a fatal error ?" "how should I
represent myself in human-readable form", and so on.

-- chis
 
Q

qu0ll

Michael Rauscher said:
qu0ll said:
Is this the way to do it? Now to convert all I do is:

ReturnValue x = ReturnValue.convert(method());

But this seems silly to have to define the int values of each enum value
effectively twice. Is there a better (simpler) way?

public static ReturnValue convert( int value ) {
ReturnValue result = null; // or: = ReturnValue.UNDEFINED
ReturnValue values[] = ReturnValue.values();
int i = 0;
while ( i < values.length && result == null )
if ( values.value == value )
result = values;
else
i++;

return result;
}

Bye
Michael


Thanks, that's a neat solution. I didn't realise there was a values()
method.

--
And loving it,

qu0ll
______________________________________________
(e-mail address removed)
(Replace the "SixFour" with numbers to email)
 
R

Robert Klemme

Michael Rauscher said:
qu0ll said:
Is this the way to do it? Now to convert all I do is:

ReturnValue x = ReturnValue.convert(method());

But this seems silly to have to define the int values of each enum value
effectively twice. Is there a better (simpler) way?
public static ReturnValue convert( int value ) {
ReturnValue result = null; // or: = ReturnValue.UNDEFINED
ReturnValue values[] = ReturnValue.values();
int i = 0;
while ( i < values.length && result == null )
if ( values.value == value )
result = values;
else
i++;

return result;
}

Bye
Michael


Thanks, that's a neat solution. I didn't realise there was a values()
method.


IMHO there are neater solutions:

package enums;

public enum ReturnValue {

POSITIVE, NEGATIVE, EITHER, UNDEFINED;

public static ReturnValue convert1( int i ) {
for ( ReturnValue current : values() ) {
if ( current.ordinal() == i ) {
return current;
}
}

return UNDEFINED;
}

public static ReturnValue convert2( int i ) {
return values();
}

public static ReturnValue convert3( int i ) {
try {
return values();
} catch ( ArrayIndexOutOfBoundsException e ) {
return UNDEFINED;
}
}

public static ReturnValue convert4( int i ) {
final ReturnValue[] v = values();
return i >= 0 && i < v.length ? v : UNDEFINED;
}
}

- no explicit int needed, enum comes with ordinal() already
- less complex conversion

Kind regards

robert
 
J

Jeffrey Schwab

Chris said:
Unlike C and C++ Java's enums are /not/ a way to give more readable names to
integer values. They are objects (with -- like all objects -- their own
behaviour suited to whatever tasks they will be asked to perform). You should
make up your mind whether you want to work with integer values (as returned by
your original routine) or with objects.

Nit: C++ enums are first-class types. Like Java enums, they have
associated ordinals, but you cannot (for example) assign a value of
AnEnumType to a variable of type SomeOtherEnumType.
 
R

Ralf Wiebicke

Hi!

How about this:

public static ReturnValue convert(int value)
{
return ReturnValue.class.getEnumConstants()[value];
}

Best regards,
Ralf.
 
C

Chris Uppal

Jeffrey Schwab wrote:

[me:]
Nit: C++ enums are first-class types. Like Java enums, they have
associated ordinals, but you cannot (for example) assign a value of
AnEnumType to a variable of type SomeOtherEnumType.

Agreed, and I suspect that the OP's motivation was a desire for that kind of
"type safety".

But, Java doesn't have a way to do that. So it's either ints or objects -- and
no middle ground ;-)

-- chris
 
Joined
Oct 2, 2006
Messages
1
Reaction score
0
I think the java enum was designed with an explicit goal in mind: forbids the conversion from integers.. Nonetheless, I had a similar situation where we needed to deserialize an integer from a non-java stream. So the following is my solution:


Code:
import java.util.TreeMap;

enum Numbers {
  ZERO(0), ONE(1);
  
  private int _value;
  
  Numbers(int value) {
    _value = value;
  }
  
  public int value() {
    return _value;
  }

  private static TreeMap<Integer, Numbers> _map;
  static {
	_map = new TreeMap<Integer, Numbers>();
    for (Numbers num: Numbers.values()) {
    	_map.put(new Integer(num.value()), num);
    }
  }
  
  public static Numbers lookup(int value) {
	  return _map.get(new Integer(value));
  }
}



public class TestEnum {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println(Numbers.lookup(0));
	}

}


qu0ll said:
I have built a simple enum class for storing various known int return values
from a particular method. It looks like this:

public enum ReturnValue
{
POSITIVE(0),
NEGATIVE(1),
EITHER(2),
UNDEFINED(3);

private int value;

public int value()
{
return value;
}

ReturnValue(int value)
{
this.value = value;
}
}

Now I face the issue of how to convert the int return value from the method
into one of these enum values. My solution was to add this method to the
enum class:

public static ReturnValue convert(int value)
{
switch (value)
{
case 0:
return POSITIVE;
case 1:
return NEGATIVE;
case 2:
return EITHER;
case 3:
return UNDEFINED;
default:
return UNDEFINED;
}

Is this the way to do it? Now to convert all I do is:

ReturnValue x = ReturnValue.convert(method());

But this seems silly to have to define the int values of each enum value
effectively twice. Is there a better (simpler) way?

--
And loving it,

qu0ll
______________________________________________
(e-mail address removed)
(Replace the "SixFour" with numbers to email)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top