This week's book giveaway is in the Mac OS forum.
We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes cast int to an enum Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "cast int to an enum" Watch "cast int to an enum" New topic
Author

cast int to an enum

Jesse House
Greenhorn

Joined: Oct 22, 2005
Posts: 4
I am using latest version of java which supports enums, I am trying to cast an integer value to set an enum variable but get compile errors,
any help would be greatly appreaciated, my actual code is more complicated then the example below.

i.e.

compilation error 'Cannot cast from int to Fruit'
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
Yeah, you can't simply cast an int to an enum, because they are too different. It's like trying to cast an apple to an orange - you can't. However there is a way to convert (not cast) an int to a Fruit:

The "ordinal" is the int associated with an enum value's position in the list of values. It starts at 0, not 1 (despite the fact that this contradicts conventional mathematical definitions of the word "ordinal"). You can look up the ordinal for a given Fruit using the ordinal() method - so

will print 0.


"I'm not back." - Bill Harding, Twister
Mark Spritzler
ranger
Sheriff

Joined: Feb 05, 2001
Posts: 17250
    
    6

"JLH"-
Welcome to the JavaRanch! Please adjust your displayed name to meet the

JavaRanch Naming Policy.

You can change it

here.

Thanks! and welcome to the JavaRanch!

Mark


Perfect World Programming, LLC - Two Laptop Bag - Tube Organizer
How to Ask Questions the Smart Way FAQ
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
Yes - the name that was on the account last night was perfectly valid. But "JLH" is not.
Jesse House
Greenhorn

Joined: Oct 22, 2005
Posts: 4
whoops, I didn't know about the rules of the Display Name, I set it to my standard screen name after creating the post last night, I have fixed the issue.

Jim, thanks for the help with the enum, worked like a charm!
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
Glad to hear it, Jesse - thanks for the prompt name fix.
 
GeeCON Prague 2014
 
subject: cast int to an enum