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?
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.
equals method uses == operator internally to check if two enum are equal. This means, You can compare Enum using both == and equals method.
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.
We can compare enum variables using the following ways. Using Enum. compareTo() method. compareTo() method compares this enum with the specified object for order.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With