【问题标题】:The method put(Character, Integer) in the type HashMap<Character,Integer> is not applicable for the arguments (char, int)HashMap<Character,Integer> 类型中的 put(Character, Integer) 方法不适用于参数 (char, int)
【发布时间】:2017-07-04 23:02:55
【问题描述】:

我收到此错误,但我不知道为什么。

这是我的代码:

char a[]=str.toCharArray();
    HashMap <Character,Integer> hm=new HashMap<Character,Integer>();
    for(int i=0;i<a.length;i++){
        if(hm.containsKey(a[i])){
            hm.put(a[i], hm.get(a[i])+1);
        }
    }

【问题讨论】:

  • 尝试清理并重建项目。但是,条件hm.containsKey(a[i]) 永远不会是true,因为在执行for 循环时HashMap hm 是空的,所以我不确定你想在那里实现什么。
  • 我的登录未完成。在其他部分我做了类似 hm.put(a[i], 1);
  • @d.j.brown 我按照你的建议做了。我仍然遇到同样的错误。
  • 它看起来像是 IDE 会发出的警告。只要我将str 定义为String,我就可以使用jdk_1.8.0_131 很好地编译您的代码,例如String str = "abc";.
  • 这正是我定义我的 str 的方式。你认为重新安装 eclipse 会起作用吗?

标签: java hashmap


【解决方案1】:

代码符合并正确执行(我刚刚添加了缺失字符的初始化hm.put(a[i], 1);)。

char a[]=str.toCharArray();
HashMap<Character,Integer> hm=new HashMap<Character,Integer>();
for(int i=0;i<a.length;i++){
    if(hm.containsKey(a[i])){
        hm.put(a[i], hm.get(a[i])+1);
    }else{
        hm.put(a[i], 1);
    }
}

严格来说编译器是正确的,因为char 不是Character 并且int 不是Integer,但是自动装箱应该会处理这个问题。

所以我们缺少一些上下文。

我可以重现相同错误的唯一方法是在测试类中添加一个模拟字符类,如下所示:

public class OneTest {

    private class Character{
    }
    @Test
    public void test() {
        String str = "AABcDD";
        char a[]=str.toCharArray();
        HashMap<Character,Integer> hm=new HashMap<Character,Integer>();
        for(int i=0;i<a.length;i++){
            if(hm.containsKey(a[i])){
                hm.put(a[i], hm.get(a[i])+1);
            }else{
                hm.put(a[i], 1);
            }
        }
        System.out.println(hm);
    }

}

【讨论】:

    猜你喜欢
    • 2015-03-09
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    • 2022-11-05
    • 1970-01-01
    • 2013-02-13
    • 2021-12-03
    • 1970-01-01
    相关资源
    最近更新 更多