hashCode和equals方法的理解

2020-06-02  本文已影响0人  泓落飞涯

1.介绍

1.1 equals方法

equals方法是Object对象中定义的方法,该方法的原意是:比较的两个对象内容/值是否相等。

Object.equals方法默认实现的是用==,即比较是否指向同一个对象:

public class Object {
    //...
    public boolean equals(Object obj) {
        return (this == obj);
    }
    //...
}

1.2 hashCode方法

JavaDoc对hashcode方法的介绍:

Returns a hash code value for the object. This method is supported for the benefit of hash tables such as those provided by java.util.HashMap.
The general contract of hashCode is:

As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the Java™ programming language.)

翻译结果:

返回对象的哈希码值。设计此方法目的是为了哈希表所服务的,例如java.util.HashMap提供的哈希表。hashCode的一般约定为:

在合理可行的范围内,由Object类定义的hashCode方法确实为不同的对象返回不同的整数。 (通常通过将对象的内部地址转换为整数来实现,但是Java™编程语言不需要此实现技术。)

hashCode方法也是Obejct对象所定义的,它存在的意义就是为哈希表所服务,但是此方法定义了几个约束条件,总结地来说就两条,也是任何Java程序员必须掌握的两条规则:

两个对象的hashcode相同,其值不一定相等。
两个对象的值相等,必须要使hashcode相等。

Object的hashCode方法默认实现是native的:

public class Object {
    //...
    public native int hashCode();
    //...
}

两个对象的hashcode相同,其值不一定相等的例子:

public class HashTest {
  public static void main(String[] args) {
    String s = "a";
    Integer aInt = 97;
    System.out.println(s.hashCode()); // 97
    System.out.println(aInt.hashCode()); // 97
  }
}

2. 实战案例

2.1 背景介绍

创建一个User对象,里面拥有一个name和age属性,按照业务要求,内容属性值相等则两个对象就相等,请重写equals和hashCode方法。

public class User {
  private String name;
  private Integer age;

  public User(String name, Integer age) {
    this.name = name;
    this.age = age;
  }
  
  // getter and setter
}

2.2 重写equals

  @Override
  public boolean equals(Object obj) {
    if (this == obj) {
      return true;
    }
    if (obj == null) {
      return false;
    }
    if (this.getClass() != obj.getClass()) {
      return false;
    }
    User target = (User) obj;
    return this.name.equals(target.getName()) && this.age.equals(target.getAge());
  }

2.3 重写hashCode

  @Override
  public int hashCode() {
    int result = 17;
    result = 31 * result + (name == null? 0: name.hashCode());
    result = 31 * result + (age == null? 0: age.hashCode());
    return result;
  }

3. 面试题

3.1 重写equals方法为什么一定要重写hashcode方法?

浅层次解读:

从出处来讲:这是Object对象的JavaDoc中为equals方法定义的约定条件。
从使用角度来讲:hashCode为像HashMap等使用哈希表的对象提供服务。是怎么提供服务的呢?请看深层次解读。

深层次解读:

当使用hashmap的put方法时,如果key为我们定义的对象,
那么计算hashmap的bucket/槽位时就需要调用key对象的hashcode方法,
也就是说key对象的hashcode方法就决定了存储在map中的bucket位置,
要是两个对象值相等(只重写了equals方法而没有重写hashcode方法的话),
就无法保证两个对象落在同一个bucket中,从而导致容器不可用。

HashMap计算key的规则和方法:

    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }
    
    static final int hash(Object key) {
        int h;
        // 调用了key对象的hashCode方法
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

示例:

public class HashTest {
  public static void main(String[] args) {
    HashMap<User, String> map = new HashMap<>();
    User user1 = new User("Tom", 20);
    User user2 = new User("Tom", 20);
    map.put(user1, user1.getName() + ":" + user1.getAge());
    System.out.println(map.get(user2)); // null
    System.out.println(map.containsKey(user2)); // false
  }
}

由于user1和user2内容相同,按照业务需求,往map中存了user1,那么用user2去查也就应该是可以查得到内容的。

public class HashTest {
  public static void main(String[] args) {
    HashMap<User, String> map = new HashMap<>();
    User user1 = new User("Tom", 20);
    User user2 = new User("Tom", 20);
    map.put(user1, user1.getName() + ":" + user1.getAge());
    System.out.println(map.get(user2)); // Tom:20
    System.out.println(map.containsKey(user2)); // true
  }
}
上一篇 下一篇

猜你喜欢

热点阅读