Is this naive equal, hashcode OK?

I have a class representing DB records with a unique Id attribute. Is it possible 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; } 
+7
source share
4 answers

In general, yes. If all identifiers are small consecutive integers, you can get the best performance from large collections using a function that allocated bits more widely over the 32 available bits. But it should work differently.

+2
source

I do not see anything wrong with this code. However, there are some questions you might think:

  • Can you have more than one object with the same id ?
  • Will the class be classified by subclass?
+1
source

The problem with using id to establish equality is that you may need to compare objects that have not yet been assigned an identifier to objects with identifiers. In this case, the equals and hashCode methods must use business fields that make the object unique (the "business key").

Also compares the class, instead of using instanceof, eliminates subclassing, as NPE says.

This code is bearable, this is not my favorite way to do something. For simple cases, it overflows, the hashCode and equal methods defined by Object will be executed. For more advanced domain models, this is inadequate, because subclasses and comparisons by business key will really be useful.

0
source

You said in your comments that the class is final, then I would suggest that the design should be the same as in Integer.equals

 public boolean equals(Object obj) { if (obj instanceof Integer) { return value == ((Integer)obj).intValue(); } return false; } 
0
source

All Articles