zoukankan      html  css  js  c++  java
  • java中重写equals()方法时为什么要重写hashCode()方法

    转载自:https://blog.csdn.net/qq_28051453/article/details/52701171

    一、什么是hashCode()、equals()方法?

    二、hashCode(),equals()两种方法是什么关系?

    三、为什么在重写equals方法的时候要重写hashCode的方法?

    四、怎么重写这两种方法?

     

     

     

     

     

          public class SimpleDemo {
        // 部门
        private String department;
        // 工号
        private int id;
     
        public SimpleDemo(int id, String department) {
            super();
            this.id = id;
            this.department = department;
        }
     
        public int getId() {
            return id;
        }
     
        public void setId(int id) {
            this.id = id;
        }
     
        public String getdepartment() {
            return department;
        }
     
        public void setdepartment(String department) {
            this.department = department;
        }
     
        @Override
        public int hashCode() {
            int hash = 1;
            hash = hash * 17 + id;
            hash = hash * 31 + department.hashCode();
            return hash;
        }
           @Override
        public boolean equals(Object obj) {
            if (obj == null)
                return false;
            if (obj == this)
                return true;
            if (obj instanceof SimpleDemo) {
                SimpleDemo sd = (SimpleDemo) obj;
                return sd.department.equals(department) && sd.id == id;
            }
            return false;
        }
    ————————————————
    版权声明:本文为CSDN博主「南瓜灯cc」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
    原文链接:https://blog.csdn.net/qq_28051453/article/details/5270117

  • 相关阅读:
    Java 正则表达式
    【 D3.js 进阶系列 — 4.0 】 绘制箭头
    d3.js path路径
    java equals 与 hashCode
    ubuntu14 简单安装ffmpeg
    mysql 导入
    Session的生命周期
    Mysql 乱码配置
    51nod1416(dfs)
    51nod1402(贪心)
  • 原文地址:https://www.cnblogs.com/Yi-ling/p/14511273.html
Copyright © 2011-2022 走看看