我在哈希映射中添加了2個對象,但2個值的關鍵字是相同的。甚至實現了hashcode和equals方法。但仍然是表示2個值,而不是3.HashMap的工作流程
代碼:
package test1;
import java.util.HashMap;
public class HashMapDemo {
int i;
String abc;
HashMapDemo(int a,String b){
i=a;
abc=b;
}
public String toString(){
return i +abc;
}
public static void main(String[] args){
HashMapDemo obj1= new HashMapDemo(2,"hello");
HashMapDemo obj2= new HashMapDemo(3,"world");
HashMapDemo obj3= new HashMapDemo(4,"around");
toDos t1=new toDos("aa");
toDos t2=new toDos("bb");
toDos t3=new toDos("aa");
HashMap test=new HashMap();
test.put(t1,obj1);
test.put(t2, obj2);
test.put(t3,obj3);
System.out.println(test.size()+""+test.get(obj2)+test);
}
}
代碼鍵:
package test1;
import java.util.HashMap;
class toDos
{
String a;
toDos(String b){
a=b;
}
public boolean equals(Object obj){
System.out.println("call of equals");
if((toDos)obj instanceof toDos & (toDos)obj !=null){
toDos temp = (toDos) obj;
if(temp.a.equals(this.a)){
return true;
}
}
return false;
}
public int hashCode(){
System.out.println("call of hasCode");
return (a!=null)? a.hashCode():0;
}
public String toString(){
return a;
}
}
你不能*擁有*「2個值的鍵是相同的」。密鑰在HashMap中是* unique *。 –
做'System.out.println(test.put(t3,obj3))'。放置HashMap將返回與該鍵關聯的先前值 –