Implementing hashCode() : hashCode « Utility Classes « SCJP






It's legal for a hashCode() method to return the same value for all instances.

transient variables aren't appropriate for equals() and hashCode().



public class MainClass {
  public int x;

  MainClass(int xVal) {
    x = xVal;
  }

  public boolean equals(Object o) {
    if (o instanceof MainClass == false) {
      return false;
    }
    MainClass h = (MainClass) o;
    if (h.x == this.x) {
      return true;
    } else {
      return false;
    }
  }

  public int hashCode() {
    return (x * 2);
  }
}








8.4.hashCode
8.4.1.Implementing hashCode()