0

我在使用函数 containsKey 时遇到了一些问题。我写了一个小程序来显示我期望 containsKey 给我一个不同的结果:

HashMap<IdentifierInterface, Set<NaturalNumberInterface>> hashMap;
HashMap<StringBuffer, Integer> works;

TryHashmap(){
    hashMap = new HashMap<IdentifierInterface, Set<NaturalNumberInterface>>();
    works = new HashMap<StringBuffer, Integer>();
}
private void start() {      
    Identifier iden = new Identifier('a');
    NaturalNumber nn = new NaturalNumber('8');
    Set<NaturalNumberInterface> set = new Set<NaturalNumberInterface>();
    set.insert(nn);

    hashMap.put(iden, set);
    System.out.println(hashMap.containsKey(iden));

    Identifier newIden = new Identifier('a');
    System.out.println(hashMap.containsKey(newIden)); //TODO why is this not true?

    iden.init('g');
    System.out.println(hashMap.containsKey(iden));
}

public static void main(String[] argv) {
    new TryHashmap().start();
}

Identifier 类的构造函数如下,init() 类似,但它会删除之前标识符中的任何内容。

Identifier(char c){
    iden = new StringBuffer();
    iden.append(c);
}

我使用标识符作为键将某些内容放入哈希图中,但是当我尝试使用具有不同名称但内容相同的标识符时,containsKey 函数在我期望为真的地方返回假。(输出打印真假真)

提前致谢!

4

2 回答 2

1

为标识符对象实现equals()hashCode()hashCode需要找到相关的桶,并且equals需要在散列时处理冲突。

延伸阅读

于 2017-01-19T05:51:06.880 回答
0

方法containsKeyHashMap.class

/**
 * Returns <tt>true</tt> if this map contains a mapping for the
 * specified key.
 *
 * @param   key   The key whose presence in this map is to be tested
 * @return <tt>true</tt> if this map contains a mapping for the specified
 * key.
 */
public boolean containsKey(Object key) {
    return getEntry(key) != null;
}

方法getEntryHashMap.class

   /** 
     * Returns the entry associated with the specified key in the 
     * HashMap.  Returns null if the HashMap contains no mapping 
     * for the key. 
     */  
    final Entry<K,V> getEntry(Object key) {  
        int hash = (key == null) ? 0 : hash(key.hashCode());  
        for (Entry<K,V> e = table[indexFor(hash, table.length)];  
             e != null;  
             e = e.next) {  
            Object k;  
            if (e.hash == hash &&  
                ((k = e.key) == key || (key != null && key.equals(k))))  
                return e;  
        }  
        return null;  
    }  

该方法getEntry告诉我们,结果将是true,只有当 Object与 Objecta相同并且hashCode()ba.equals(b)

于 2017-01-19T06:11:29.433 回答