1. 程式人生 > >hashCode與equals的聯絡與區別

hashCode與equals的聯絡與區別

一、equals方法的作用

1、預設情況(沒有覆蓋equals方法)下equals方法都是呼叫Object類的equals方法,而Object的equals方法主要用於判斷物件的記憶體地址引用是不是同一個地址(是不是同一個物件)。

2 、要是類中覆蓋了equals方法,那麼就要根據具體的程式碼來確定equals方法的作用了,覆蓋後一般都是通過物件的內容是否相等來判斷物件是否相等。

沒有覆蓋equals方法程式碼如下:

    //學生類  
    public class Student {  
        private int age;  
        private
String name; public Student() { } public Student(int age, String name) { super(); this.age = age; this.name = name; } public int getAge() { return age; } public String getName
() { return name; } public void setAge(int age) { this.age = age; } public void setName(String name) { this.name = name; } } 測試 程式碼如下: [java] view plain copy import java.util.HashSet; import java.util.LinkedList; import java.util.Set; public
class EqualsTest { public static void main(String[] args) { LinkedList<Student> list = new LinkedList<Student>(); Set<Student> set = new HashSet<Student>(); Student stu1 = new Student(3,"張三"); Student stu2 = new Student(3,"張三"); System.out.println("stu1 == stu2 : "+(stu1 == stu2)); System.out.println("stu1.equals(stu2) : "+stu1.equals(stu2)); list.add(stu1); list.add(stu2); System.out.println("list size:"+ list.size()); set.add(stu1); set.add(stu2); System.out.println("set size:"+ set.size()); } } 執行結果: stu1 == stu2 : false stu1.equals(stu2) : false list size:2 set size:2

結果分析:Student類沒有覆蓋equals方法,stu1呼叫equals方法實際上呼叫的是Object的equals方法。所以採用物件記憶體地址是否相等來判斷物件是否相等。因為是兩個新物件所以物件的記憶體地址不相等,所以stu1.equals(stu2) 是false。

3、我們覆蓋一下equals方法(age和name屬性),讓Student類其通過判斷物件的內容是否相等來確定物件是否相等。

覆蓋後的Student類:

//學生類  
    public class Student {  
        private int age;  
        private String name;  

        public Student() {  
        }  
        public Student(int age, String name) {  
            super();  
            this.age = age;  
            this.name = name;  
        }  
        public int getAge() {  
            return age;  
        }  
        public String getName() {  
            return name;  
        }  
        public void setAge(int age) {  
            this.age = age;  
        }  
        public void setName(String name) {  
            this.name = name;  
        }  
        @Override  
        public boolean equals(Object obj) {  
            if (this == obj)  
                return true;  
            if (obj == null)  
                return false;  
            if (getClass() != obj.getClass())  
                return false;  
            Student other = (Student) obj;  
            if (age != other.age)  
                return false;  
            if (name == null) {  
                if (other.name != null)  
                    return false;  
            } else if (!name.equals(other.name))  
                return false;  
            return true;  
        }  

    }  


執行結果:

stu1 == stu2 : false
stu1.equals(stu2) : true
list size:2
set size:2

結果分析:因為Student兩個物件的age和name屬性相等,而且又是通過覆蓋equals方法來判斷的,所示stu1.equals(stu2) 為true。注意以上幾次測試list和set的size都是2

二、HashCode

4、通過以上的程式碼執行,我們知道equals方法已經生效。接下來我們在覆蓋一下hashCode方法(通過age和name屬性來生成hashcode)並不覆蓋equals方法,其中Hash碼是通過age和name生成的。

覆蓋hashcode後的Student類:

 //學生類  
    public class Student {  
        private int age;  
        private String name;  

        public Student() {  
        }  
        public Student(int age, String name) {  
            super();  
            this.age = age;  
            this.name = name;  
        }  
        public int getAge() {  
            return age;  
        }  
        public String getName() {  
            return name;  
        }  
        public void setAge(int age) {  
            this.age = age;  
        }  
        public void setName(String name) {  
            this.name = name;  
        }  
        @Override  
        public int hashCode() {  
            final int prime = 31;  
            int result = 1;  
            result = prime * result + age;  
            result = prime * result + ((name == null) ? 0 : name.hashCode());  
            return result;  
        }     
    }  


執行結果:

stu1 == stu2 : false
stu1.equals(stu2) : false
list size:2
hashCode :775943
hashCode :775943
set size:2

結果分析:我們並沒有覆蓋equals方法只覆蓋了hashCode方法,兩個物件雖然hashCode一樣,但在將stu1和stu2放入set集合時由於equals方法比較的兩個物件是false,所以就沒有在比較兩個物件的hashcode值。

5、我們覆蓋一下equals方法和hashCode方法。

Student程式碼如下:

   //學生類  
    public class Student {  
        private int age;  
        private String name;  
        public Student() {  
        }  
        public Student(int age, String name) {  
            super();  
            this.age = age;  
            this.name = name;  
        }  
        public int getAge() {  
            return age;  
        }  
        public String getName() {  
            return name;  
        }  
        public void setAge(int age) {  
            this.age = age;  
        }  
        public void setName(String name) {  
            this.name = name;  
        }  
        @Override  
        public int hashCode() {  
            final int prime = 31;  
            int result = 1;  
            result = prime * result + age;  
            result = prime * result + ((name == null) ? 0 : name.hashCode());  
            System.out.println("hashCode : "+ result);  
            return result;  
        }  
        @Override  
        public boolean equals(Object obj) {  
            if (this == obj)  
                return true;  
            if (obj == null)  
                return false;  
            if (getClass() != obj.getClass())  
                return false;  
            Student other = (Student) obj;  
            if (age != other.age)  
                return false;  
            if (name == null) {  
                if (other.name != null)  
                    return false;  
            } else if (!name.equals(other.name))  
                return false;  
            return true;  
        }  

    }  


執行結果:

stu1 == stu2 : false

stu1.equals(stu2) :true

list size:2

hashCode :775943

hashCode :775943

set size:1

結果分析:stu1和stu2通過equals方法比較相等,而且返回的hashCode值一樣,所以放入set集合中時只放入了一個物件。

6、下面我們讓兩個物件equals方法比較相等,但hashCode值不相等試試。

Student類的程式碼如下:

 //學生類  
    public class Student {  
        private int age;  
        private String name;  
        <span style="color:#ff0000;">private static int index=5;</span>  
        public Student() {  
        }  
        public Student(int age, String name) {  
            super();  
            this.age = age;  
            this.name = name;  
        }  
        public int getAge() {  
            return age;  
        }  
        public String getName() {  
            return name;  
        }  
        public void setAge(int age) {  
            this.age = age;  
        }  
        public void setName(String name) {  
            this.name = name;  
        }  
        @Override  
        public int hashCode() {  
            final int prime = 31;  
            int result = 1;  
            result = prime * result + <span style="color:#ff0000;">(age+index++)</span>;  
            result = prime * result + ((name == null) ? 0 : name.hashCode());  
            <span style="color:#ff0000;">System.out.println("result :"+result);</span>  
            return result;  
        }  
        @Override  
        public boolean equals(Object obj) {  
            if (this == obj)  
                return true;  
            if (obj == null)  
                return false;  
            if (getClass() != obj.getClass())  
                return false;  
            Student other = (Student) obj;  
            if (age != other.age)  
                return false;  
            if (name == null) {  
                if (other.name != null)  
                    return false;  
            } else if (!name.equals(other.name))  
                return false;  
            return true;  
        }  

    }  

執行結果:

stu1 == stu2 : false
stu1.equals(stu2) : true
list size:2
hashCode :776098
hashCode :776129
set size:2

結果分析:雖然stu1和stu2通過equals方法比較相等,但兩個物件的hashcode的值並不相等,所以在將stu1和stu2放入set集合中時認為是兩個不同的物件。

7、修改stu1的某個屬性值

Student程式碼如下:

 //學生類  
    public class Student {  
        private int age;  
        private String name;  
        public Student() {  
        }  
        public Student(int age, String name) {  
            super();  
            this.age = age;  
            this.name = name;  
        }  
        public int getAge() {  
            return age;  
        }  
        public String getName() {  
            return name;  
        }  
        public void setAge(int age) {  
            this.age = age;  
        }  
        public void setName(String name) {  
            this.name = name;  
        }  
        @Override  
        public int hashCode() {  
            final int prime = 31;  
            int result = 1;  
            result = prime * result + age;  
            result = prime * result + ((name == null) ? 0 : name.hashCode());  
            System.out.println("hashCode : "+ result);  
            return result;  
        }  
        @Override  
        public boolean equals(Object obj) {  
            if (this == obj)  
                return true;  
            if (obj == null)  
                return false;  
            if (getClass() != obj.getClass())  
                return false;  
            Student other = (Student) obj;  
            if (age != other.age)  
                return false;  
            if (name == null) {  
                if (other.name != null)  
                    return false;  
            } else if (!name.equals(other.name))  
                return false;  
            return true;  
        }  

    }  


測試程式碼如下:

[java] view plain copy

    import java.util.HashSet;  
    import java.util.LinkedList;  
    import java.util.Set;  


    public class EqualsTest {  
        public static void main(String[] args) {  
            LinkedList<Student> list = new LinkedList<Student>();  
            Set<Student> set = new HashSet<Student>();  
            Student stu1  = new Student(3,"張三");  
            Student stu2  = new Student(3,"張三");  
            System.out.println("stu1 == stu2 : "+(stu1 == stu2));  
            System.out.println("stu1.equals(stu2) : "+stu1.equals(stu2));  
            list.add(stu1);  
            list.add(stu2);  
            System.out.println("list size:"+ list.size());  

            set.add(stu1);  
            set.add(stu2);  
            System.out.println("set size:"+ set.size());  
            stu1.setAge(34);  
            System.out.println("remove stu1 : "+set.remove(stu1));  
            System.out.println("set size:"+ set.size());  
        }  

    }  


執行結果:

stu1 == stu2 : false
stu1.equals(stu2) : true
list size:2
hashCode : 775943
hashCode : 775943
set size:1
hashCode : 776904
remove stu1 : false
set size:1

結果分析:

當我們將某個物件存到set中時,如果該物件的屬性參與了hashcode的計算,那麼以後就不能修改該物件參與hashcode計算的那些屬性了,否則會引起意向不到的錯誤的。正如測試中,不能夠移除stu1物件。
總結:

1、equals方法用於比較物件的內容是否相等(覆蓋以後)

2、hashcode方法只有在集合中用到

3、當覆蓋了equals方法時,比較物件是否相等將通過覆蓋後的equals方法進行比較(判斷物件的內容是否相等)。

4、將物件放入到集合中時,首先判斷要放入物件的hashcode值與集合中的任意一個元素的hashcode值是否相等,如果不相等直接將該物件放入集合中。如果hashcode值相等,然後再通過equals方法判斷要放入物件與集合中的任意一個物件是否相等,如果equals判斷不相等,直接將該元素放入到集合中,否則不放入。

5、將元素放入集合的流程圖:

6、HashSet中add方法原始碼:

 public boolean add(E e) {  
        return map.put(e, PRESENT)==null;  
        }  

map.put原始碼:
    <pre name="code" class="java"> public V put(K key, V value) {  
            if (key == null)  
                return putForNullKey(value);  
            int hash = hash(key.hashCode());  
            int i = indexFor(hash, table.length);  
            for (Entry<K,V> e = table[i]; e != null; e = e.next) {  
                Object k;  
                if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {  
                    V oldValue = e.value;  
                    e.value = value;  
                    e.recordAccess(this);  
                    return oldValue;  
                }  
            }  

            modCount++;  
            addEntry(hash, key, value, i);  
            return null;  
        }</pre>  
    <pre></pre>  
    <pre></pre>