Converting between different enums?

Q

qazmlp1209

enum firstEnum
{
ONE, TWO, THREE
}

enum secondEnum
{
ONE, TWO, THREE
}


public static void main( String args[] )
{
firstEnum firstEnumVal = firstEnum.ONE ;
secondEnum secondEnumVal = (secondEnum) firstEnumVal ;//Error is
reported here.
}

As you can see above, the integer values of the constants of both the
enums are assumed to be same(coincidentally the name also in the above
example). In that case, how exactly I can convert from one enum type to
another?
 
I

Ian Pilcher

As you can see above, the integer values of the constants of both the
enums are assumed to be same(coincidentally the name also in the above
example). In that case, how exactly I can convert from one enum type to
another?

You can use toString and valueOf. A better approach is to add a method
to one of both enum types which converts to the other.

Since the whole point of using enums is to create distinct types,
however, I can't see a good reason to be doing this.
 
K

Kenneth P. Turvey

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

On Mon, 13 Mar 2006 07:36:36 -0800, qazmlp1209 wrote:

[Snip]
public static void main( String args[] )
{
firstEnum firstEnumVal = firstEnum.ONE ;
secondEnum secondEnumVal = (secondEnum) firstEnumVal ;//Error is
reported here.
}

As you can see above, the integer values of the constants of both the
enums are assumed to be same(coincidentally the name also in the above
example). In that case, how exactly I can convert from one enum type to
another?

In Java, enums aren't the same as integers. The value firstEnum.ONE has
no relationship to the value secondEnum.ONE unless you write the code to
make them related.

- --
Kenneth P. Turvey <[email protected]>

XMPP IM: (e-mail address removed)
Yahoo IM: kpturvey2
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.1 (GNU/Linux)

iD8DBQFEFgNAi2ZgbrTULjoRAqjzAJwNSIx9vqtZ0v17U5Y4eSwUDmqVLgCeLoBX
q2tPGxmTqByzcVO5C+y3wUI=
=4u2B
-----END PGP SIGNATURE-----
 

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

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top