This week's book giveaway is in the OCAJP forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide 1Z0-808 and have Jeanne Boyarsky & Scott Selikoff on-line! See this thread for details.
I am using some info from a database and assigning it to the various instance variables of an object. Mostly the info from the database is a String, so I have very simple setter methods for these that take the String from the ResultSet and assign it to the relevant String instance variables of my object.
So far so good. What I've come unstuck on is that one of my object's instance variables is a reference to an enum, which I want to use as it's been suggested to me that it would make my code more readable. This can't be stored (I don't think) in a database, so I thought I could just store an int in the database and use this int as an argument to my object's setter method, which has code that uses that int as the index in the enum.
I've read up on enums and looked at the docs, and none of the methods allow you to say "I want the enum at index 2", which seems a bit odd to me as I would have thought lots of people would want to do that. Does anybody know if this is possible?
I think I could create an EnumMap with an int value as the key and the corresponding Enum as the value and use the EnumMap's get(Object key) method to return the enum, but this seems very long winded to me and I would be grateful for a second opinion.
I took a look at the language specification. I won't pretend I understood too much, but based on what you said, I've implemented the following code which works:
Do you think this is the best way? Better than (or maybe similar to) an EnumMap?
Also I was wondering why the values() method was not in the docs.
Thanks for your help
Joined: Oct 24, 2008
Thanks as well Henry.
I will explore those methods.
Joined: Oct 13, 2005
There is a problem that the enum in the database and the enum in Java must have the same members, so EDB ⊂ EJava, otherwise there is a risk of a value coming from the database which doesn't correspond to the values in your enum.
The reason it isn't in the API is that the values() method is a static member of the type you write, not of the Enum<E> class. But the values method is mentioned in the Java™ Tutorials page. If you ever find the Java5 version of the Java Tutorials, look what it says about enums and enumerated types in other languages
subject: Issue with assigning enum instance variable