package com.example;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * equals和hashCode的理解<br/>
 * http://www.cnblogs.com/skywang12345/p/3324958.html
 *
 * @author VanceKing
 * @since 2017/3/31.
 */

public class EqualsAndHash {
    public static void main(String[] args) {
        test1();
    }
    

    //重写 equals(),但是没有重写 hashCode(),HashMap 存在多条相同的记录
    // 正确的做法是两个方法都要同时重写
    private static void test1() {
        Person person1 = new Person("123456", "Vance");
        Person person2 = new Person("123456", "Vance");

        System.out.println("person1 == person2: " + (person1 == person2));
        System.out.println("person1.equals(person2): " + person1.equals(person2));

        HashMap<Person, String> map = new HashMap<>();
        map.put(person1, person1.name);
        map.put(person2, person2.name);
        for (Map.Entry<Person, String> entry : map.entrySet()) {
            System.out.println(entry.getKey().toString() + " --- " + entry.getValue());
        }
    }

    private static class Person {
        private String idNumber;
        private String name;

        public Person(String idNumber, String name) {
            this.idNumber = idNumber;
            this.name = name;
        }

        @Override public boolean equals(Object o) {
            if (o == null) {
                return false;
            }
            if (!(o instanceof Person)) {
                return false;
            }
            final Person person = (Person) o;

            return idNumber.equals(person.idNumber);
        }

        @Override public int hashCode() {
            return Objects.hash(idNumber, name);
        }

        @Override public String toString() {
            return "Person{" +
                    "idNumber='" + idNumber + '\'' +
                    ", name='" + name + '\'' +
                    '}';
        }
    }
}

@@ -1324,15 +1324,26 @@
  == 
-null) %7B
+this) %7B//%E5%AF%B9%E8%B1%A1%E8%87%AA%E8%BA%AB%EF%BC%8C%E6%8F%90%E9%AB%98%E6%95%88%E7%8E%87
 %0A   
@@ -1354,36 +1354,35 @@
          return 
-fals
+tru
 e;%0A            %7D
@@ -1374,32 +1374,123 @@
 ;%0A            %7D%0A
+            // 1. %E5%B7%B2%E7%BB%8F%E5%8C%85%E5%90%AB null %E5%88%A4%E6%96%AD %0A            // 2. %E4%B8%8D%E5%BA%94%E8%AF%A5%E9%80%9A%E8%BF%87 Class %E5%88%A4%E6%96%AD%EF%BC%8C%E5%90%A6%E5%88%99%E5%B0%86%E4%B8%8D%E9%80%82%E5%90%88%E4%B9%8B%E7%B1%BB%E7%BB%A7%E6%89%BF%E7%88%B6%E7%B1%BB equals() %E7%9A%84%E6%83%85%E5%86%B5%0A
             if (
@@ -1605,16 +1605,36 @@
 son) o;%0A
+            //%E5%BF%85%E8%A6%81%E7%9A%84%E5%9F%9F%E5%88%A4%E6%96%AD
 %0A       

equals hashCode