java中的Map判断重复的方法

来源:互联网 发布:magnet关联的软件 编辑:程序博客网 时间:2024/05/16 09:36

本人推测是先用hash值判断后用equals()方法判断,如果有其一不等,则表示两对象不等。以下程序可验证

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

public class MapDemo04 {

public static void main(String[] args) {
Map <Person04,String>map=new HashMap<Person04, String>();
Person04 person=new Person04("abcd");
map.put(new Person04("zhangsan"), "a");
map.put(new Person04("haha"), "b");
map.put(new Person04("sadff"), "c");
map.put(person, "abc");
map.put(person, "cba");
Set <Map.Entry<Person04, String>> s=map.entrySet();
Iterator <Map.Entry<Person04, String>>iterator=s.iterator();
while(iterator.hasNext()){
Map.Entry<Person04, String> me=iterator.next();
System.out.println(me.getKey()+"  "+me.getValue());
}
}


}
class Person04{
String name;
Person04(String name){
this.name = name;
}
public String toString(){
return this.name;
}
public int hashCode(){
return 1;
//return this.name.hashCode();         //***********1
}
public boolean equals(Object o){

//return true;                                    //***********2
return false;

}

}

现在把两方法中的注释移下,注释上行或是下行,2*2=4种组合看下执行结果就可以得到推测结果