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;
  }

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.


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?

  • The problem with using id to establish equality is that you might want to compare objects that haven't been assigned an id yet to objects that have ids. In that case then the equals and hashCode methods must use the business fields that make the object unique (the "business key").

    Also comparing the class instead of using instanceof rules out subclassing, like NPE says.

    This code is tolerable, it's not my preferred way of doing things. For the simple cases it's overkill, the hashCode and equals methods defined by Object will get the job done. For the more advanced domain models it's inadequate, because subclassing and comparisons by business key will actually be useful.

    链接地址: http://www.djcxy.com/p/12400.html

    上一篇: Aptana UI主题

    下一篇: 这是天真的等于,哈希码可以吗?