首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java util hashmap containsKey()

Java util hashmap containsKey()
EN

Stack Overflow用户
提问于 2017-01-19 13:47:40
回答 2查看 1.7K关注 0票数 0

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

代码语言:javascript
复制
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()类似,但它将删除之前标识符中的所有内容。

代码语言:javascript
复制
Identifier(char c){
    iden = new StringBuffer();
    iden.append(c);
}

我使用标识符作为键将某些内容放入hashmap中,但是当我尝试使用具有不同名称但具有相同内容的标识符时,containsKey函数返回false,而我期望返回true。(输出打印true false true)

提前感谢!

EN

回答 2

Stack Overflow用户

发布于 2017-01-19 13:51:07

为标识符对象实现equals()hashCode()。需要hashCode来查找相关的存储桶,并且需要equals来处理哈希过程中的冲突。

Further Reading

票数 1
EN

Stack Overflow用户

发布于 2017-01-19 14:11:29

HashMap.class中的containsKey方法

代码语言:javascript
复制
/**
 * 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;
}

HashMap.class中的getEntry方法

代码语言:javascript
复制
   /** 
     * 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告诉我们,只有当对象a具有与对象ba.equals(b)相同的hashCode()时,结果才会是b

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41734622

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档