Skip to Main Content

Java APIs

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Do I need to override enum's hashCode() and equals()?

843793Nov 4 2008 — edited Nov 4 2008
Hi all:
I have a enum type let's say it is
public enum Type
{
  ONE,
  TWO;
}
If I want to compare the enum value to see if they are same value or not, let's say I have two:
Type a = Type.ONE;
Type b = Type.TWO;
should I use
 a.equals(b)
or
(a == b)
If I want to use it as another class's key field, and I want to override this class hashCode() and equals() methods.
Can enum Type return the correctly hash code?

For example the class is like:
public Class A 
{
  Type type;
  pubilc boolean equals(Object other)
  {
    // here skip check class type, null and class cast
    if(other.type.equals(this.type))
       return true;
    else
     return false;
  }

  public int hashCode()
  {
    int result = 31;
    result += 31 * result + type.hashCode() ;
   // can we get correct hash code from enum here? 
    return result;
  }
}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Dec 2 2008
Added on Nov 4 2008
1 comment
316 views