zoukankan      html  css  js  c++  java
  • equals方法与hashcode方法

    //当我们想要进行对象(自己新建的)之间的比较的时候我们需要重写对象的equals方法和hashcode方法 若a.equals(b)==true 则a.hashcode()==b.hashcode一定成立,反之不成立!!!
    public class Person
    {
        private String id;
        private String name;
        //重写equals方法分为4个部分
        public boolean equals(Object obj)
        {

      //1:先判断obj是否为空
            if (obj == null)
            {
                return false;
            }

      //2 再判断obj是否==内部对象
            if (obj == this)
            {
                return true;
            }

      //判断类型是否一样
            if (obj.getClass() != this.getClass())
            {
                return false;
            }

      //类中的所有的属性都要进行比较
            Person p = (Person) obj;
            return this.getId().equals(p.getId())
                    && this.getName().equals(p.getName());
        }

        public String getId()
        {
            return id;
        }

        public String getName()
        {
            return name;
        }

        @Override
        public int hashCode()
        {

      //20是随机取的 还可以取17 50等
            int result = 20;
            result = result * 31 + this.name.hashCode();
            result = result * 31 + this.id.hashCode();
            return result;
        }

        public void setId(String id)
        {
            this.id = id;
        }

        public void setName(String name)
        {
            this.name = name;
        }

        @Override
        public String toString()
        {
            return "Person [id=" + id + ", name=" + name + "]";
        }
    }

    //测试类

    public class Test
    {
        public static void main(String[] args)
        {
            Person p1 = new Person();
            Person p2 = new Person();
            p1.setId("11");
            p1.setName("wangChao");
            p2.setId("11");
            p2.setName("wangChao");
            // 测试重写的equals方法
            System.out.println(p1.equals(p2));
            Set<Person> s = new HashSet<Person>();
            s.add(p1);
            s.add(p2);
            // 测试重写的hashcode方法
            System.out.println(s);
        }
    }

  • 相关阅读:
    Linux之文件处理命令
    Linux基础命令
    rip实验
    Linux基础之磁盘分区
    mysql安装
    centos Apache、php、mysql默认安装路径
    You probably tried to upload too large file. Please refer to documentation for ways to workaround this limit.
    Wrong permissions on configuration file, should not be world writable!
    机器会学习么 学习总结
    实验 5 Spark SQL 编程初级实践
  • 原文地址:https://www.cnblogs.com/qingtianBKY/p/7423553.html
Copyright © 2011-2022 走看看