Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / September 2006

Tip: Looking for answers? Try searching our database.

How do I convert an int to an enum?

Thread view: 
qu0ll - 18 Sep 2006 09:26 GMT
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?

Signature

And loving it,

qu0ll
______________________________________________
qu0llSixFour@gmail.com
(Replace the "SixFour" with numbers to email)

Hendrik Maryns - 18 Sep 2006 10:00 GMT
qu0ll schreef:
> I have built a simple enum class for storing various known int return values
> from a particular method.  It looks like this:

<snip>

> {
>    switch (value)
[quoted text clipped - 12 lines]
>
> 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.
Signature

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

qu0ll - 18 Sep 2006 10:14 GMT
> qu0ll schreef:
>> I have built a simple enum class for storing various known int return
[quoted text clipped - 28 lines]
>
> 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?

Signature

And loving it,

qu0ll
______________________________________________
qu0llSixFour@gmail.com
(Replace the "SixFour" with numbers to email)

Chris Uppal - 18 Sep 2006 11:11 GMT
> 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
Jeffrey Schwab - 18 Sep 2006 14:45 GMT
>> 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
[quoted text clipped - 5 lines]
> 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.
Chris Uppal - 19 Sep 2006 10:22 GMT
[me:]
> > 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 --
[quoted text clipped - 5 lines]
> 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
Chris Brat - 18 Sep 2006 10:29 GMT
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

> I have built a simple enum class for storing various known int return values
> from a particular method.  It looks like this:
[quoted text clipped - 53 lines]
> qu0llSixFour@gmail.com
> (Replace the "SixFour" with numbers to email)
qu0ll - 18 Sep 2006 10:42 GMT
> Hi,
>
[quoted text clipped - 10 lines]
> 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?

Signature

And loving it,

qu0ll
______________________________________________
qu0llSixFour@gmail.com
(Replace the "SixFour" with numbers to email)

Hendrik Maryns - 18 Sep 2006 11:07 GMT
qu0ll schreef:
>> Hi,
>>
[quoted text clipped - 13 lines]
> 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?

Given the situation, I think the switch statement is the way to go.

H.
Signature

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

Hendrik Maryns - 18 Sep 2006 11:06 GMT
Chris Brat schreef:
> Hi,
>
[quoted text clipped - 7 lines]
>
> 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.
Signature

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

Michael Rauscher - 18 Sep 2006 11:09 GMT
qu0ll schrieb:

> 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[i].value == value )
            result = values[i];
        else
            i++;

    return result;
}

Bye
Michael
qu0ll - 18 Sep 2006 11:32 GMT
> qu0ll schrieb:
>>
[quoted text clipped - 20 lines]
> Bye
> Michael

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

Signature

And loving it,

qu0ll
______________________________________________
qu0llSixFour@gmail.com
(Replace the "SixFour" with numbers to email)

Robert Klemme - 18 Sep 2006 12:29 GMT
>> qu0ll schrieb:
>>> Is this the way to do it?  Now to convert all I do is:
[quoted text clipped - 21 lines]
> 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()[i];
    }

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

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

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

Kind regards

    robert
Ralf Wiebicke - 19 Sep 2006 09:05 GMT
Hi!

How about this:

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

Best regards,
Ralf.


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.