1. 程式人生 > >HashMap可插入相同key的錯覺(hashcode不同 equals 相等)

HashMap可插入相同key的錯覺(hashcode不同 equals 相等)

def value ext java ret gen new map code

test1()是正常情況:當插入 相同key 時 後者會把前者覆蓋
test2()是因為插入的key p1 和 p2是2個實例對象 雖然他們在內存中的首地址不同,但他們的實際內容是相同的
所以p1和p2 的 Person類必須實現 hashcode 和equals方法 以防止 插入相同內容的key


import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class TestPerson {
    public static void test1() {
        System.out.println("User user defined class as key");
        HashMap<String,String>hm = new HashMap<String,String>();
        hm.put("aaa","bbb");
        hm.put("aaa","ccc");
        Iterator iter = hm.entrySet().iterator();
        while(iter.hasNext()) {
            Map.Entry entry = (Map.Entry)iter.next();
            String key = (String)entry.getKey();
            String val = (String)entry.getValue();
            System.out.println(key+"     "+val);
        }
    }
    public static void test2(){
        System.out.println("Use String as Key:");
        HashMap<Person,String>hm = new HashMap<Person,String>();
        Person p1 = new Person("111", "name1");
        Person p2 = new Person("111", "name1");
        hm.put(p1,"address1");
        hm.put(p2,"address2");
        Iterator iter = hm.entrySet().iterator();
        while(iter.hasNext()) {
            Map.Entry entry = (Map.Entry)iter.next();
            Person key = (Person)entry.getKey();
            String val = (String)entry.getValue();
            System.out.println(key+"     "+val);
        }

    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        test1();
        System.out.println(" ");
        test2();
    }

}

實現 hashcode和equals


import java.util.*;
 class Person {
     String id;
     String name;
     public int hashCode() {
         return id.hashCode();
     }
     public Person(String id,String name) {
         this.id = id;
         this.name = name;
     }
     public String toString() {
         return "id ="+id+",name = "+name;
     }
     public boolean equals(Object obj) {
            Person p = (Person) obj;
            if(p.id.equals(this.id))
                return true;
            else
                return false;
        }
}

HashMap可插入相同key的錯覺(hashcode不同 equals 相等)