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

Cel*_*tas 1 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());
        }
    }
Run Code Online (Sandbox Code Playgroud)

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

@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;
}
Run Code Online (Sandbox Code Playgroud)

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

rge*_*man 7

当您调用时substring,请记住结束索引不包含在子字符串中.

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

在你的电话里

input.substring(0, input.length()-1)
Run Code Online (Sandbox Code Playgroud)

你实际上是把最后一个角色从当前的任何角色中删除了input.所以,如果你有一把钥匙"finch",你无意中抬起了钥匙"finc".

我根本没有看到这个substring电话的理由; 去掉它:

Birds temp = (Birds) hint.get(input.trim());
Run Code Online (Sandbox Code Playgroud)

此外,Birds如果您向您提供泛型类型参数,则不需要强制转换HashMap,如下所示:

Map<String, Birds> hint = new HashMap<>();
Run Code Online (Sandbox Code Playgroud)

然后,当调用get时,您不再需要强制转换:

Birds temp = hint.get(input.trim());
Run Code Online (Sandbox Code Playgroud)