해시 맵에 2 개의 객체를 추가했지만 2 개의 값의 키는 같습니다. hashcode 및 equals 메소드를 구현했습니다. 하지만 여전히 두 값 대신 3HashMap의 작업 흐름
을 보여주는 코드 : 키
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;
}
}
"두 값의 키가 동일하지 않습니다". 키는 HashMap에서 * unique *입니다. –
Do'System.out.println (test.put (t3, obj3))'. HashMap put는 키와 관련된 이전 값을 리턴합니다. –