2013-02-04 2 views
-2

해시 맵에 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; 
    } 
} 
+1

"두 값의 키가 동일하지 않습니다". 키는 HashMap에서 * unique *입니다. –

+1

Do'System.out.println (test.put (t3, obj3))'. HashMap put는 키와 관련된 이전 값을 리턴합니다. –

답변

0

그것은 t1.equals(t3) 보인다 - 따라서는, t3의 삽입은 처음 삽입 한 무시 기입.

HashMap에는 각각의 고유 키가 하나의 연관된 값을 가지고 있습니다. t1t3은 서로 같기 때문에 두 개의 별개 키만 있습니다.

raw types을 사용하지 말고 가능한 한 많이 generics types을 사용해야합니다.

1

class toDos 등호 방법에 따르면 String a이 같으면 두 개체가 동일합니다. 이전 값으로 obj1가 OBJ3로 대체 할 수 있도록

HashMap test=new HashMap(); 
test.put(t1,obj1); // "aa" 
test.put(t2,obj2); // "bb" 
test.put(t3,obj3); //"aa" 

그래서으로 obj1과 obj2보다 모두 같은 객체로 취급 될 것이다.