Java Boolean Class – Why Not an Enum?

apijavasource code

It seems to me that the Boolean class is an ideal candidate to be implemented as an enum.

Looking at the source code, most of the class is static methods which could be moved unchanged to an enum, the rest become much simpler as an enum. Compare original (comments and static methods removed):

public final class Boolean implements java.io.Serializable,
                                      Comparable<Boolean>
{
   public static final Boolean TRUE = new Boolean(true);
  public static final Boolean FALSE = new Boolean(false);
   private final boolean value;
   public Boolean(boolean value) {
       this.value = value;
   }
   public Boolean(String s) {
       this(toBoolean(s));
   }
   public boolean booleanValue() {
       return value;
   }
   public String toString() {
       return value ? "true" : "false";
   }
   public int hashCode() {
       return value ? 1231 : 1237;
   }
   public boolean equals(Object obj) {
       if (obj instanceof Boolean) {
           return value == ((Boolean)obj).booleanValue();
       }
       return false;
   }
   public int compareTo(Boolean b) {
       return compare(this.value, b.value);
   }
}

with an enum version:

public enum Boolean implements Comparable<Boolean>
{
   FALSE(false), TRUE(true);
   private Boolean(boolean value) {
       this.value = value;
   }
   private final boolean value;
   public boolean booleanValue() {
       return value;
   }

   public String toString() {
       return value ? "true" : "false";
   }
}

Is there any reason why Boolean couldn't become an enum?

If this is the Sun code to override the equals() method, it is missing a very fundamental check of comparing the references of the two objects before comparing their values. This is how I think the equals() method should be:

   public boolean equals(Object obj) {

       if (this == obj) {
          return true;
       }

       if (obj instanceof Boolean) {
           return value == ((Boolean)obj).booleanValue();
       }
       return false;
   }

Best Answer

Well, I guess I could start by arguing that Java enumerations were not added to the Java programming language until the JDK 1.5. and therefore this solution was not even an alternative in the early days when the Boolean class was defined.

That being said, Java has the reputation of keeping backwards compatibility between releases and so, even if we, today, may consider your solution as a good alternative, we cannot do it without breaking thousands of lines of code out there already using the old Boolean class.