阿里Java手册剖析-6.1[强制]关于 hashCode 和 equals 的处理

511 阅读6分钟

阿里Java开发手册剖析:


[强制]关于 hashCode 和 equals 的处理,遵循如下规则:

  1. 只要重写equals,就必须重写hashCode。
  1. 因为Set存储的是不重复的对象,依据hashCode和equals进行判断,所以Set存储的 对象必须重写这两个方法。
  1. 如果自定义对象作为Map的键,那么必须重写hashCode和equals。

Demo

为了方便理解先写了个demo。

定义了一个Person类,他包含了一些属性比如:姓名、QQ号、QQ密码等。


public class Person {

    
    private String name;

    /**
     * qq账号
     */
    private String account;
    /**
     * qq密码
     */
    private String password;


    public Person(String name, String account, String password) {
        this.name = name;
        this.account = account;
        this.password = password;
    }
}

然后模拟登录QQ的场景,QQ的服务器加入是按密码和账号来存储账户的,只要密码和账号对了,就应该登录成功。 现在王麻子注册了个QQ账户,并把账户密码都给了张三和李四让他们去登录。

 public static void main(String[] args) {
       //Set模拟qq数据库
        Set<Person> qq = new HashSet<>();
        //王麻子注册了一个qq账户
        qq.add(new Person("王麻子", "111", "1111"));
        
        //张三和李四拿着王麻子的账户登录QQ
        Person zhangsan = new Person("张三", "111", "1111");
        Person lisi = new Person("李四", "111", "1111");


        System.out.println("张三能否登陆成功 " + qq.contains(zhangsan));
        System.out.println("李四能否登陆成功 " + qq.contains(lisi));
    }

日志输出:

张三能否登陆成功 false
李四能否登陆成功 false

Process finished with exit code 0

上面结果明显是不符合预期的,因为默认情况下Set会判断是否为同一个对象。 由于Person类没有重写父类的equals(Object obj)所以,它默认就是使用了父类的返回值:


class  Object{
	
    //判断是否为同一个对象 
	public boolean equals(Object obj) {
        return (this == obj);
    }
 }

只要不是同一个对象,登录就失败。 所以为了满足需求,就得重写equals(Object obj):只要账号和密码对了就是一个人就能登录。


class Person {
...

    @Override
    public boolean equals(Object obj) {
        if (obj == this) return true;

        if (obj instanceof Person) {
            return sameAccount((Person) obj) && samePassword((Person) obj);
        }
        return false;
    }
    private boolean sameAccount(Person person) {
        if (person == null || person.account.isEmpty()) {
            return false;
        }
        return this.account.equals(person.account);
    }

    private boolean samePassword(Person person) {
        if (person == null || person.password.isEmpty()) {
            return false;
        }
        return this.password.equals(person.password);
    }
 ...   
}

运行还是失败:

张三能否登陆成功 false
李四能否登陆成功 false

Process finished with exit code 0

为什么呢? 因为Set中取值先对比对象的hashCode,如果hashCode不同直接返回,不会调用equals()方法。而Person没有重写hashCode()方法,使用的就是Object默认的值:

class  Object{
	//native返回 大概率是对应了内存地址的转换值
	public native int hashCode();
 }

由于不同对象内存地址肯定不同,所以李四和张三的hashCode肯定不一样。 所以此时我们需要定义个有意义的hashCode():


class Person {
...
    @Override
    public int hashCode() {
        return this.account.hashCode() + this.password.hashCode();
    }
 ...   
}

account和password都是String,将他们的hashCode相加可以认为是一个有意义且不容易重复的值。 此时再运行demo:

张三能否登陆成功 true
李四能否登陆成功 true

Process finished with exit code 0

此时满足了需求:张三和李四拿着王麻子的QQ账号和密码也能登陆他的qq。

hashCode()和equals()在Set和Map中的调用顺序

先看下HashMap是如何获取对象的:

HashMap中的get方法的实现:先根据hashCode从Node类型的数组中找到对应的Node,然后再对比Node,只有hashCode相同且equals的key才会找对应的value

 public V get(Object key) {
       Node<K,V> e;
       return (e = getNode(hash(key), key)) == null ? null : e.value;
   }


static final int hash(Object key) {
       int h;
       return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
   }
   
  
   final Node<K,V> getNode(int hash, Object key) {
       Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
       if ((tab = table) != null && (n = tab.length) > 0 &&
           (first = tab[(n - 1) & hash]) != null) {
           if (first.hash == hash && // always check first node
               ((k = first.key) == key || (key != null && key.equals(k))))
               return first;
           if ((e = first.next) != null) {
               if (first instanceof TreeNode)
                   return ((TreeNode<K,V>)first).getTreeNode(hash, key);
               do {
                   if (e.hash == hash &&
                       ((k = e.key) == key || (key != null && key.equals(k))))
                       return e;
               } while ((e = e.next) != null);
           }
       }
       return null;
   }

HashSet的contains(Object o)的具体实现也是HashMap的上面代码:

public HashSet() {
       map = new HashMap<>();
   }


public boolean contains(Object o) {
       return map.containsKey(o);
   }

public boolean containsKey(Object key) {
       return getNode(hash(key), key) != null;
   }
   
final Node<K,V> getNode(int hash, Object key) {
       Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
       if ((tab = table) != null && (n = tab.length) > 0 &&
           (first = tab[(n - 1) & hash]) != null) {
           if (first.hash == hash && // always check first node
               ((k = first.key) == key || (key != null && key.equals(k))))
               return first;
           if ((e = first.next) != null) {
               if (first instanceof TreeNode)
                   return ((TreeNode<K,V>)first).getTreeNode(hash, key);
               do {
                   if (e.hash == hash &&
                       ((k = e.key) == key || (key != null && key.equals(k))))
                       return e;
               } while ((e = e.next) != null);
           }
       }
       return null;
   }


HashSet中add方法也是对应了HashMap中的putVal(hash(key), key, value, false, true);

下面是HashMap中put方法的源码实现:


 public V put(K key, V value) {
       return putVal(hash(key), key, value, false, true);
   }

   
   final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                  boolean evict) {
       Node<K,V>[] tab; Node<K,V> p; int n, i;
       if ((tab = table) == null || (n = tab.length) == 0)
           n = (tab = resize()).length;
           //根据hashCode去查找是否存在对应对象,没有则直接存入。
       if ((p = tab[i = (n - 1) & hash]) == null)
           tab[i] = newNode(hash, key, value, null);
       else {
       	//如果该对象存在取出来,将该对象的的hashCode与新hashCode对比。如果相同再去对比是否equals()。当然两个对象相同也是认为是相同的。如果相同,我们认为Key是一个值,此时可以替换对应的Value了。
           Node<K,V> e; K k;
           if (p.hash == hash &&
               ((k = p.key) == key || (key != null && key.equals(k))))
               e = p;
           else if (p instanceof TreeNode)
               ...
           else {
               ...
           }
           ...
       }
      ...
       return null;
   }

从上面可以看出,hashCode()比equals()先调用。而且hashCode作为类似数组的index来取值,所以消耗比较小。因此有意义的hashCode()是可以减少equals()的调用,提高应用性能。

解释: Object.java中的public int hashCode()上关于这个方法的注释有一段如下:

If two objects are equal according to the {@code equals(Object)} method, then calling the {@code hashCode} method on each of the two objects must produce the same integer result.

意思大体是:如果两个对象通过equals(Object)方法来比较认为是 等同的,那么他们的hashCode方法返回的整形数值一定 一样的

不过需要注意:如果两个对象通过equals(Object)方法认为不相同的,他们的hashCode不一定需要是不同的。

由上可知道,两个相同的对象HashCode肯定相同,不同的对象HashCode也可能相同。所以HashCode不同的两个对象肯定不相同

JVM在存储对象时,先根据HashCode去寻找,如果该HashCode对应的位置没哟对象,直接存放。如果有对象就调用equals(Object)进行比较,如果两者相同,那么就不存储。如果两者不同的话,就作为一个新对象存储在该HashCode对应的链表上。

Java语言中equals(Object)的默认实现是比较的是内存地址,HashCode()默认返回的是内存地址的应设值。

将一个对象作为Key存储在Set或者HashMap中,比较这个值是否相同是先比较HashCode。如果只修改equals(Object)会出现你认为相同的对象,在Set和HashMap中认为不是通过值。

总结

其实如果对象如果不是用来作为离散列表的离散值。其实不一定需要重写在重写equals方法时,一定就要重写hashCode方法。只是普通的比较两个对象内容是否相等,根本无需调用HashCode()。但是在将对象作为Set或者HashMap这类容器的Key时,则必须根据需求重新定义HashCode()。比如String.java就在重写equals(Object)时重写了hashCode(),因为我们经常将String类型的数据作为HashMap的Key。

其实没有必须的,还是要理解原理和项目需求。

修改如下:

对于关于 hashCode 和 equals 的处理,遵循如下规则:

  1. 如果将自定义的对象作为Map的键,那么只要重写equals(Object),就必须重写hashCode(),因为Map中会调用equals(Object)hasCode()方法来作为键唯一的判断。

  2. Set用于存储的是不重复的对象,也会使用hasCode()equals(Object)方法进行唯一性的判断,所以Set存储的对象只要重写equals(Object),就必须重写hashCode()

  3. Map和Set中会优先对比hashCode()的返回值,再调用。所以优质的hashCode()定义可以还能减少equals(Objec)调用次,提高性能。

  4. 由于自定义的对象在任何时候都可能被作为Map的键或者存储到Set中,所以可以强制在重写equals(Objec),就必须重写hashCode()。可以参考String源码。