为什么在hashmap中找不到密钥?

时间:2014-01-23 22:29:09

标签: java hashmap

我打印出要搜索的密钥和地图中的密钥,但是它们在那里,但是分配失败了。我通过用一个对象填充地图进行测试,然后检查并打印出键。我引用的关键是那里,所以我看不到temp是如何为空?

    Birds temp = (Birds)hint.get(input.substring(0, input.length()-1).trim());//the last char is being dropped off on purpose
    if(temp == null)
    {
        System.out.println("failed to map key");
        Iterator entries = hint.entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry thisEntry = (Map.Entry) entries.next();
            System.out.println("Key1: "+ 
                thisEntry.getKey()); //this an next line printout the same
            System.out.println("key2: "+
                input.substring(0, input.length()-1).trim());
        }
    }

我在鸟类中添加了以下几行,但仍然存在同样的问题

@Override public int hashCode()
    {
        return name.hashCode();
    }

@Override
public boolean equals(Object obj) {
    Bird b = (Bird)obj;
    String str = b.name;
    if(str.compareTo(this.name) == 0)
        return true;
    else
        return false;
}

原来白色空间搞砸了,我没有经常给trim()打电话。

1 个答案:

答案 0 :(得分:7)

当您致电substring时,请记住结束索引不包含在子字符串中。

  

子字符串从指定的beginIndex开始,并扩展到索引endIndex - 1处的字符

在你的电话中

input.substring(0, input.length()-1)

你实际上是从input当前的任何一个角色中取出最后一个角色。因此,如果您有一个密钥"finch",则无意中查找了密钥"finc"

我根本没有看到substring电话的原因;删除它:

Birds temp = (Birds) hint.get(input.trim());

此外,如果您向Birds提供了通用类型参数,则无需转换为HashMap,如下所示:

Map<String, Birds> hint = new HashMap<>();

然后,当调用get时,您不再需要演员:

Birds temp = hint.get(input.trim());
相关问题