Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this naive equals, hashcode OK?

I have a class representing DB-Entries with a unique Id attribute. Is is OK to implement the equals() and hashcode() methods only based on this attribute

  @Override public int hashCode()
  { return id;
  }

  @Override public boolean equals(Object obj)
  {
    if (this == obj)                  return true;
    if (obj == null)                  return false;
    if (getClass() != obj.getClass()) return false;
    Task other = (Task) obj;
    if (id != other.id)
      return false;
    return true;
  }
like image 270
mica Avatar asked Mar 15 '13 15:03

mica


People also ask

What is the hashCode () and equals () used for?

Java hashCode() An object hash code value can change in multiple executions of the same application. If two objects are equal according to equals() method, then their hash code must be same. If two objects are unequal according to equals() method, their hash code are not required to be different.

Why you should override equals or hashCode?

Case 1: Overriding both equals(Object) and hashCode() method Whenever it(hashcode) is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified.

What are equals () and hashCode () overriding rules?

"If two objects are equal using Object class equals method, then the hashcode method should give the same value for these two objects." So, if in our class we override equals() we should override hashcode() method also to follow this rule.

What happens if you override equals but not hashCode?

Overriding only equals() method without overriding hashCode() causes the two equal instances to have unequal hash codes, which violates the hashCode contract (mentioned in Javadoc) that clearly says, if two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two ...


2 Answers

In general, yes. If all the ids are small consecutive integers, you could get better performance from big collections by using a function which distributed the bits more widely throughout the available 32 bits. But this should work find otherwise.

like image 153
Ernest Friedman-Hill Avatar answered Oct 22 '22 23:10

Ernest Friedman-Hill


I don't see anything wrong with this code. However, there are some questions you might wish to ponder:

  • Can you ever have more than one object with the same id?
  • Will the class ever be subclassed?
like image 42
NPE Avatar answered Oct 22 '22 22:10

NPE