Skip to main content
gamedev.net
🔒 Locked

[java] Enumerations In Java

Started by jonnii Oct 28, 2002 at 11:01 AM 4 replies 1k views
Original Post
jonnii
jonnii
In C++ and C# its possible to created enumerated values like enum{january, february...}; ... is this possible in java? All the documentation i''ve seen on enumerations is related to enumerated link lists or other data structures... is there another way to do what i am trying? please help! -jonnii
-jonnii=========jon@voodooextreme.comwww.voodooextreme.com
Viro
Viro
In Java, what you should do is replace the enum with a class that contains public static variables

class MyEnum {
public static final int JANUARY = 1;
....
}
"Linux is not about free software, it is about community," -- Steve Balmer, Microsoft Chief Executive.
Arild Fines
Arild Fines
There is another recommended idiom to make up for the lack of an enum type. It basically goes something like this:


  

public class MyEnum
{
private MyEnum()
{
//empty

}

public static final MyEnum SOMETHING = new MyEnum( );
public static final MyEnum SOMETHINGELSE = new MyEnum();
public static final MyEnum ANDNOWFORSOMETHINGCOMPLETELYDIFFERENT = new MyEnum( );
}

You can now use this almost like a C# enum:

  
public void SomeMethod( MyEnum state )
{
if ( state == MyEnum.SOMETHING )
doSomething();
}

This is a lot more typesafe than the final int solution.



Faith. n. Belief without evidence in what is told by one who speaks without knowledge, of things without parallel. -- Ambrose Bierce
--AnkhSVN - A Visual Studio .NET Addin for the Subversion version control system.[Project site] [IRC channel] [Blog]
HenryApe
HenryApe
I have read that a simple typesafe enumeration mechanism is scheduled for inclusion in the Java 1.5 release. Meanwhile I think Arild''s pattern works best, or possibly the class in the Apache foundation''s Avalon project that supports adding the enums to maps in order to allow iteration and other operations.
misterX
misterX
The solution given by Arild Fines is indeed the most usefull, the best to work with. Despite of this, it's not 100% typesafe, it has a small subtle trap when working together with serialisation. If you do so, you'll need to take special precautions. The problem is described in this article.


[edited by - misterX on November 2, 2002 12:38:45 PM]
c_wraith
c_wraith
Yeah, it has a trap related to serialization. But it''s not the only one. There''s also the class loader issue, and that one has no solution.

Basically, a class is only defined in relation to its class loader. If there are multiple class loaders in use, there can be multiple versions of the same class in use. When that happens, they are distinct classes, even though they have the same name, so their static fields will be different objects.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.