HashMap的工作流程

时间:2013-02-04 07:10:27

标签: java

我在哈希映射中添加了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;
    }   
}

2 个答案:

答案 0 :(得分:1)

根据class toDos的等于方法,如果String a相同,则两个对象都相同。

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

因此,Obj1和obj2都将被视为同一个对象,因此您的旧值obj1将被替换为obj3。

答案 1 :(得分:0)

似乎t1.equals(t3) - 因此,插入t3会覆盖第一个插入的条目。

HashMap中,每个不同的密钥都有一个关联值 - 由于t1t3彼此相等 - 您只有2个不同的密钥。

作为附注 - 您应该避免使用raw types并尽可能使用generics types