【问题标题】:Can not for each in HashMap [duplicate]不能为HashMap中的每个[重复]
【发布时间】:2018-12-12 10:53:53
【问题描述】:

我尝试使用 for 每个循环来遍历 HashMap 键,但它没有编译。

这是我的代码:

import java.util.Map;
import java.util.HashMap;

public class theseeker{
    public static void main(String[] args){

        Map blue = new HashMap<Character,Integer>();
        for(char c = 'a';c <= 'z';c++)
            blue.put(new Character(c),new Integer((int)c));

        for(Character c : blue.keySet())
            System.out.println(c);


    }


}

我收到此错误:

 Object cannot be converted to Character
        for(Character c : blue.keySet())
                                     ^

是不是因为使用了界面?

【问题讨论】:

    标签: java dictionary hashmap


    【解决方案1】:

    您将地图默认设置为设置它的演员

    Map<Character, Integer> blue = new HashMap<>();
    

    清理代码后,它应该如下所示

    public static void main(String[] args) {
        Map<Character, Integer> blue = new HashMap<>();
    
        for (char c = 'a'; c <= 'z'; c++) {
            blue.put(c, (int) c);
        }
    
        for (Character c : blue.keySet()) {
            System.out.println(c);
        }
    }
    

    【讨论】:

    • 谢谢它有效。因此,当我使用接口 Map 时,我必须指定键和值的 Base_type。我说的对吗?
    • 不,你不是已经指定了&lt;Character, Integer&gt;
    • 好的,我现在知道了。接口映射的默认类型是 ,当我尝试使用每个循环类型进行迭代时,对象无法转换为字符,因此我必须定义具有适当类型的接口。谢谢
    猜你喜欢
    • 2015-12-28
    • 2018-05-01
    • 1970-01-01
    • 2020-08-30
    • 1970-01-01
    • 1970-01-01
    • 2015-04-10
    • 2019-07-23
    • 2015-01-22
    相关资源
    最近更新 更多