我在哈希图中添加了 2 个对象,但 2 个值的键是相同的。甚至实现了 hashcode 和 equals 方法。但它仍然显示 2 个值而不是 3 个。
代码:
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;
}
}