String value -> enum constant??

Q

qazmlp1209

I have an enum like this:

public enum GRADE {
ONE, TWO, THREE
}

I need to do the mapping from the corresponding string values to one of
these enum values. If the String value is "ONE", then the enum value
ONE should be assigned.
For example:
enum GRADE = someThing ("ONE") ;

Now, the GRADE should be assigned ONE.

What should someThing be replaced with here, for the above to
work(without changing the definition of GRADE)?
 
C

Chris Uppal

What should someThing be replaced with here, for the above to
work(without changing the definition of GRADE)?

Why not use a Map<String, GRADE> ?

-- chris
 
B

Boris Stumm

I have an enum like this:

public enum GRADE {
ONE, TWO, THREE
}

I need to do the mapping from the corresponding string values to one of
these enum values. If the String value is "ONE", then the enum value
ONE should be assigned.
For example:
enum GRADE = someThing ("ONE") ;

GRADE grade = GRADE.valueOf("ONE");
 
T

Tony Morris

I have an enum like this:

public enum GRADE {
ONE, TWO, THREE
}

I need to do the mapping from the corresponding string values to one of
these enum values. If the String value is "ONE", then the enum value
ONE should be assigned.
For example:
enum GRADE = someThing ("ONE") ;

Now, the GRADE should be assigned ONE.

What should someThing be replaced with here, for the above to
work(without changing the definition of GRADE)?

A similar question has been asked here:
http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=1&t=013824

Hopefully this helps.
 
Q

qazmlp1209

That helped!
Now, I would like to get the exact String equivalent of the enum
constants. The direct typecasting does not seem to help. Is there a
way?

------
class Enum_to_String
{
public enum myEnum
{
ONE, TWO, THREE
}

public static void main( String args[] )
{
String ONEStr = (String) myEnum.ONE ; // Error is reported here.
// How
to make ONEStr="ONE"?
System.out.println( "ONEStr:" +ONEStr ) ;
}
}
------
 
T

tom fredriksen

That helped!
Now, I would like to get the exact String equivalent of the enum
constants. The direct typecasting does not seem to help. Is there a
way?

enums are somewhat like classes, you can have fields, methods and
constructors etc, but it is limited compared to classes. Search the
group there was an example of recently.

/tom
 

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,774
Messages
2,569,599
Members
45,173
Latest member
GeraldReund
Top