Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative to enum in Java 1.4

Since Java 1.4 doesn't have enums I'm am doing something like this:

public class SomeClass {
     public static int SOME_VALUE_1 = 0;
     public static int SOME_VALUE_2 = 1;
     public static int SOME_VALUE_3 = 2;

     public void receiveSomeValue(int someValue) {
            // do something
     }
 }

The caller of receiveSomeValue should pass one those 3 values but he can pass any other int. If it were an enum the caller could only pass one valid value.

Should receiveSomeValue throw an InvalidValueException?

What are good alternatives to Java 5 enums?

like image 860
Daniel Moura Avatar asked Jun 24 '09 13:06

Daniel Moura


People also ask

Why enums should not be used?

Enums are good to represent static/singleton objects but should never be used as value objects or have attributes that get set during usage. You can use an enum to 'type/label' a two week duration, but the actual start/end dates should be attributes of a class DateRange.

Can Java enum be compared with ==?

equals method uses == operator internally to check if two enum are equal. This means, You can compare Enum using both == and equals method.

Can enum be generic Java?

The enum is a default subclass of the generic Enum<T> class, where T represents generic enum type. This is the common base class of all Java language enumeration types. The transformation from enum to a class is done by the Java compiler during compilation. This extension need not be stated explicitly in code.

Can enums be compared?

We can compare enum variables using the following ways. Using Enum. compareTo() method. compareTo() method compares this enum with the specified object for order.


2 Answers

Best to use in pre 1.5 is the Typesafe Enum Pattern best described in the book Effective Java by Josh Bloch. However it has some limitations, especially when you are dealing with different classloaders, serialization and so on.

You can also have a look at the Apache Commons Lang project and espacially the enum class, like John has written. It is an implementation of this pattern and supports building your own enums.

like image 74
Roland Schneider Avatar answered Oct 15 '22 11:10

Roland Schneider


I'd typically create what I call a constant class, some thing like this:

public class MyConstant 
{
  public static final MyConstant SOME_VALUE = new MyConstant(1);
  public static final MyConstant SOME_OTHER_VALUE = new MyConstant(2);
  ...

  private final int id;


  private MyConstant(int id)
  {
    this.id = id;
  }

  public boolean equal(Object object) 
  {
    ...
  }

  public int hashCode() 
  {
    ...
  }
}

where equals and hashCode are using the id.

like image 37
Nick Holt Avatar answered Oct 15 '22 12:10

Nick Holt