When Java overwrites equals always overwrite hashcode

  • 2020-05-19 04:54:10
  • OfStack

When Java overwrites equals, always overwrite hashcode

Recently, I have learned the basic knowledge of java. When I encounter Java covering equals, I always need to cover hashcode. After direct discussion with my colleagues and online inquiry, I will sort out the information here to help you understand.

Specific implementation code:


package cn.xf.cp.ch02.item9;

import java.util.HashMap;
import java.util.Map;

public class PhoneNumber
{
  private final short areaCode;
  private final short prefix;
  private final short lineNumber;
  
  public PhoneNumber(int areaCode, int prefix, int lineNumber)
  {
    rangeCheck(areaCode, 999, "area code");
    rangeCheck(prefix, 999, "prefix");
    rangeCheck(lineNumber, 9999, "line number");
    this.areaCode = (short) areaCode;
    this.prefix = (short) prefix;
    this.lineNumber = (short) lineNumber;
  }
  
  private static void rangeCheck(int arg, int max, String name)
  {
    if (arg < 0 || arg > max)
      throw new IllegalArgumentException(name + ": " + arg);
  }
  
  @Override
  public boolean equals(Object o)
  {
    if (o == this)
      return true;
    if (!(o instanceof PhoneNumber))
      return false;
    PhoneNumber pn = (PhoneNumber) o;
    return pn.lineNumber == lineNumber && pn.prefix == prefix && pn.areaCode == areaCode;
  }
  
  /*
  @Override
  // As to why it is used 31 , this is the recommended value, and studies have shown that this number performs better 
  public int hashCode()
  {
    int result = 17;
    result = 31 * result + areaCode;
    result = 31 * result + prefix;
    result = 31 * result + lineNumber;
    return result;
  }
  */
  
  // if 1 The hash code is cached inside the object if the object is not changed very often and is expensive 
  // with volatile The thread reads the most modified value of the variable every time it USES the variable. 
  private volatile int hashcode;
  
  @Override
  public int hashCode()
  {
    int result = hashcode;
    if (result == 0)
    {
      result = 17;
      result = 31 * result + areaCode;
      result = 31 * result + prefix;
      result = 31 * result + lineNumber;
      hashcode = result;
    }
    
    return result;
  }
  
  public static void main(String[] args)
  {
    Map<PhoneNumber, String> m = new HashMap<PhoneNumber, String>();
    m.put(new PhoneNumber(707, 867, 5309), "Jenny");
    // There is no return jenny Oh, it will null This is because put Objects put them into different hash buckets 
    System.out.println(m.get(new PhoneNumber(707, 867, 5309)));
  }
}

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: