java-关于hashCode()和equals()的重写

11 篇文章 0 订阅

很久之前看了一篇半吊子文章,理解错了。去参加了个面试,跟别人滔滔不绝的讲了半天,结果回来一查,错了,好尴尬!辣鸡害人不浅。现在我就总结一下,踩过的坑,含着泪也要填了。先来看下面试官怎么问的。

为什么要重写hashCode()和equals()?

其实我们平时用的多的就是集合里的对象判断是否相等。比如说HashMap中put一个键值对,看它的底层方法实现:

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

我们看到方法里调用了一个hash函数,具体实现如下:

  static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

可以看到它没有直接用key的hash值,而是跟默认数组长度取了个模。我们知道,随机的hashCode碰撞的概率很小。我们通过取模的方式,让每个值都能均匀的存放在链表上。

言归正传,虽然put是对象的hashCode跟一个数取模,但是我们来看看HashMap是怎么来取值的。

/*
*判断
*/
public boolean containsKey(Object key) {
        return getNode(hash(key), key) != null;
    }

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

/*
*根据key remove
*/
 public V remove(Object key) {
        Node<K,V> e;
        return (e = removeNode(hash(key), key, null, false, true)) == null ?
            null : e.value;
    }

我们看到它们都用到了上面提到的hash()方法。

然而当我们要定义一个对象作为HashMap的key的时候,如果我们不在这个对象内重写hashCode()和equals()的话,他们都会用父类的hashCode()和equals()。也就是Object的。而Object的hashCode()返回的是对象在内存中的地址。equals()也是比较的是两个对象的堆上的地址是否相同,也就是说是不是同一块内存。就是说比较的是他们是不是他们自己。下面举个栗子:

定义一个对象Student,没有重写hashCode()和equals()

@Getter
@Setter
@ToString
public class Student {
   private Double sn;
   private String name;
   private String className;

    public Student(double sn, String name, String className) {
        this.sn = sn;
        this.name = name;
        this.className = className;
    }
}

然后,我们new这个对象,放到HashMap中然后,再:

public class TestDemo {
    public static void main(String[] args) {
        Map<Student, Integer> urlMap = new HashMap<>();
        Student student1 = new Student(12345,"simon","class_2");
        System.out.println(student1.hashCode());
        urlMap.put(student1, 123);
        Student student2 = new Student(12345,"simon","class_2");
        System.out.println(student2.hashCode());
        System.out.println(urlMap.get(student2));
    }
}

打印出的结果是:

两串数字就是两个对象的地址。我们调用的hashCode()和equals()也是Object的方法

因为对象是放在堆上的,每次new就是一个新的内存空间,而每一块内存空间都有一个自己的地址。

只重写hashCode()不重写equals()可以吗?

   @Override
    public int hashCode() {
        int result = 17;
        result = result * 31 + sn.hashCode();
        result = result * 31 + name.hashCode();
        result = result * 31 + className.hashCode();
        return result;
    }

我们发现HashCode一样了,但还是返回null,到底为什么呢?我们来看看,get方法是如何实现的:

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

    /**
     * Implements Map.get and related methods
     *
     * @param hash hash for key
     * @param key the key
     * @return the node, or null if none
     */
    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;
    }

流程大概是:

  1. 先根据key的HashCode跟数组长度取余得到特殊的Hash值,
  2. 确定数组中元素的位置,然后根据算出的特殊hash值获取链表首节点,
  3. 遍历链表寻找有没有相同的 key,判断依据是 e.hash == hash && ((k = e.key) == key || key.equals(k))

由于没有重写equals(),此处的key.equals(k)比较的是我们传入对象的地址,和之前put进当前节点的key对象的地址。所以没有匹配的值。所以轮询完毕后最终返回null

重写equals()

  @Override
    public boolean equals(Object o) {
        if (this == o)
            return true;
        if (o == null)
            return false;
        if (getClass() != o.getClass())
            return false;
        Student student = (Student) o;
        if (name == null) {
            if (student.name != null)
                return false;
        } else if (!name.equals(student.name))
            return false;
        if (className == null) {
            if (student.className != null)
                return false;
        } else if (!className.equals(student.className))
            return false;
        if (sn == null) {
            if (student.sn != null)
                return false;
        } else if (!sn.equals(student.sn))
            return false;
        return true;
    }

运行结果:

重写了equals()就必须重写hashCode()?

是因为我们要做的是两个对象的比较,如果不重写hashCode(),我们连集合内对象都找不到,还怎么去比较他们的内容。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值