zoukankan      html  css  js  c++  java
  • 为什么要重写equals和hashcode

      我在最开始遇到这个问题时是很疑惑地,因为我只重写了equals但是并没有出现什么问题。其实首先要明白一点的是重写equals时重写hashcode

    并不是java语法层面的问题。而是一种通用约定。因为java中基于散列的集合实现了这个约定。所以当你的类在集合这样的数据结构中使用,也需要遵守这种约定。

    不然就会出错。下面是一个例子。

    public class EqualsAndHashcode {
        /**
         * 显然 我们的目的是对于name 和 age 相同的对象 都返回的是同一个值
         * @param args
         */
        public static void main(String[] args) {
            Map<Student, String> map = new HashMap<>();
            Student one = new Student("tom", 12);
            map.put(one, "one");
            Student two = new Student("tom", 12);
            System.out.println(map.get(two));
        }
    }
    
    class Student {
        String name;
        int age;
    
        public Student(String name, int age) {
            this.name = name;
            this.age = age;
        }
    }

    如果没有重写 equals和hashcode显然 输出的是null.

     @Override
        public boolean equals(Object obj) {
            if (obj == this) {
                return true;
            }
            if (obj instanceof Student) {
                Student student = (Student) obj;
                return student.age==this.age&&student.name.equals(this.name);
            }
            return false;
        }

    如果只重写equals 输出的依然是null

     @Override
        public int hashCode() {
            int result = 13;
            result = result * 37 + age;
            result = result * 37 + name.hashCode();
            return result;
        }

    重写hashcode之后 ,可以输出one.

    public class EqualsAndHashcode {
    public static void main(String[] args) {
    Map<Student, String> map = new HashMap<>();
    Student one = new Student("tom", 12);
    map.put(one, "one");
    Student two = new Student("tom", 12);
    System.out.println(map.get(two));
    }
    }

    class Student {
    String name;
    int age;

    public Student(String name, int age) {
    this.name = name;
    this.age = age;
    }
  • 相关阅读:
    Liunx运维(七)-用户管理及用户信息查询命令
    容器网络原理分析:veth 和 network namespace
    浅谈 Docker 网络:单节点多容器
    浅谈 Docker 网络:单节点单容器
    图图图
    LinkPrediction可能有用的数据集
    2021年展望
    2020年总结
    毕业设计:基于web的外卖订餐系统的设计与实现
    机器学习和数据分析在实体识别方面的简单应用
  • 原文地址:https://www.cnblogs.com/shaomys/p/11834266.html
Copyright © 2011-2022 走看看