zoukankan      html  css  js  c++  java
  • 关于equals和hashCode

    Collection中的remove和contains方法,都是挨个比较每个对象是否equals参数中的对象,如果equals了,就remove掉或者包含。

    看下面例子:

    package com.cy.container;
    
    import java.util.ArrayList;
    import java.util.Collection;
    import java.util.HashSet;
    
    public class BasicContainer {
        public static void main(String[] args) {
            Collection c = new ArrayList();
            c.add("hello");
            c.add(new Name("f1", "l1"));
            c.add(new Integer(100));
            c.remove("hello");
            c.remove(new Integer(100));
            System.out.println(c.remove(new Name("f1", "l1")));
            System.out.println(c);
        }
    }
    
    class Name{
        private String firstName, lastName;
        
        public Name(String firstName, String lastName) {
            super();
            this.firstName = firstName;
            this.lastName = lastName;
        }
    
        public String getFirstName() {
            return firstName;
        }
    
        public String getLastName() {
            return lastName;
        }
    
        @Override
        public String toString() {
            return "Name [firstName=" + firstName + ", lastName=" + lastName + "]";
        }
    
        @Override
        public boolean equals(Object obj) {
            if (this == obj)
                return true;
            if (obj == null)
                return false;
            if (getClass() != obj.getClass())
                return false;
            Name other = (Name) obj;
            if (firstName == null) {
                if (other.firstName != null)
                    return false;
            } else if (!firstName.equals(other.firstName))
                return false;
            if (lastName == null) {
                if (other.lastName != null)
                    return false;
            } else if (!lastName.equals(other.lastName))
                return false;
            return true;
        }
        
    }
    View Code

    Collection是使用Arraylist的,只是重写了Name的equals方法,console打印:

    true
    []

    说明ArrayList的remove和contains中只是比较了equals,没有使用到hashCode。

    例子2:

    package com.cy.container;
    
    import java.util.ArrayList;
    import java.util.Collection;
    import java.util.HashSet;
    
    public class BasicContainer {
        public static void main(String[] args) {
            Collection c = new HashSet();
            c.add("hello");
            c.add(new Name("f1", "l1"));
            c.add(new Integer(100));
            c.remove("hello");
            c.remove(new Integer(100));
            System.out.println(c.remove(new Name("f1", "l1")));
            System.out.println(c);
        }
    }
    
    class Name{
        private String firstName, lastName;
        
        public Name(String firstName, String lastName) {
            super();
            this.firstName = firstName;
            this.lastName = lastName;
        }
    
        public String getFirstName() {
            return firstName;
        }
    
        public String getLastName() {
            return lastName;
        }
    
        @Override
        public String toString() {
            return "Name [firstName=" + firstName + ", lastName=" + lastName + "]";
        }
    
        @Override
        public boolean equals(Object obj) {
            if (this == obj)
                return true;
            if (obj == null)
                return false;
            if (getClass() != obj.getClass())
                return false;
            Name other = (Name) obj;
            if (firstName == null) {
                if (other.firstName != null)
                    return false;
            } else if (!firstName.equals(other.firstName))
                return false;
            if (lastName == null) {
                if (other.lastName != null)
                    return false;
            } else if (!lastName.equals(other.lastName))
                return false;
            return true;
        }
        
    }
    View Code

    Collection是使用HashSet来实现的,也只是重写了equals方法,console打印:

    false
    [Name [firstName=f1, lastName=l1]]

    并没有成功的remove掉,说明仅仅重写equals方法不行。

    那么补上hashCode方法:

    class Name{
        private String firstName, lastName;
        
        public Name(String firstName, String lastName) {
            super();
            this.firstName = firstName;
            this.lastName = lastName;
        }
    
        public String getFirstName() {
            return firstName;
        }
    
        public String getLastName() {
            return lastName;
        }
    
        @Override
        public String toString() {
            return "Name [firstName=" + firstName + ", lastName=" + lastName + "]";
        }
    
        @Override
        public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result
                    + ((firstName == null) ? 0 : firstName.hashCode());
            result = prime * result
                    + ((lastName == null) ? 0 : lastName.hashCode());
            return result;
        }
    
        @Override
        public boolean equals(Object obj) {
            if (this == obj)
                return true;
            if (obj == null)
                return false;
            if (getClass() != obj.getClass())
                return false;
            Name other = (Name) obj;
            if (firstName == null) {
                if (other.firstName != null)
                    return false;
            } else if (!firstName.equals(other.firstName))
                return false;
            if (lastName == null) {
                if (other.lastName != null)
                    return false;
            } else if (!lastName.equals(other.lastName))
                return false;
            return true;
        }
    
        
        
    }
    View Code

    再次执行:

    true
    []

    说明了什么?

     

    马士兵的解释:

      容器类对象在调用remove,contains等方法时,需要比较两个对象是不是相等,它比较这两个对象是不是相等的时候,比较的主要用到的是equals方法,但是有的时候也会用到hashCode方法,什么时候呢?
      当这个对象用在map接口里头作为键,就是作为字典的那个索引,作为那个东西使用的时候,它会使用hashCode这个方法。为什么?因为hashCode 的效率会更高。所以重写equals方法应该重写hashCode方法,也就是两个对象互相的equals,那么他们两个必须具备相同的hashCode。
      Object里面有hashCode方法,你可以通过这个hashCode实际上可以找到它在内存里的地址,当然不是绝对的物理地址,但是你通过这个hashCode你大概很快的就可以找的着它在内存里头到底存在什么位置上。所以hashCode这个东西呢,非常的适合做索引。因此,咱们有的对象,用做Map接口一对一对的往里存的时候,一个叫索引,一个叫值,用做索引的时候,很有可能别人会用它的hashCode方法。所以在这里,记得一个原则,你要重写这个对象的equals方法,你必须要重写这个对象的hashCode方法。两个对象互相的equals,两个对象必须具备相同的hashCode。
      比方说,你查字典的时候,一般的首先在索引里面查,查到某个条目的时候才去找相对应的字,在这个意义上来讲,那个索引,是一个对象,那个字是一个值,你不能说我找着了一个索引,这两个索引一样,我索引到的是不同的字,这个是不行的。
      重写equals方法,必须重写hashCode方法,什么时候有用? 这个对象当做索引的时候,当做键的时候。
     
     
  • 相关阅读:
    PHP unset销毁变量并释放内存
    编码问题
    编程中关于对时区的理解(语言PHP)
    简单树结构的实现
    设计模式
    Selenium WebDriver +Python讲解
    PS入门基础-魔幻调色
    .NET Core、.NET Standard 、ASP.NET Core 和 .NET Framework 有什么不同?
    电商设计
    NPOI相关学习文档
  • 原文地址:https://www.cnblogs.com/tenWood/p/8282617.html
Copyright © 2011-2022 走看看