【问题标题】:Not an "unsafe operation" error: Incompatible types Object cannot be converted to Entry<String, Boolean>不是“不安全操作”错误:不兼容的类型 Object 无法转换为 Entry<String, Boolean>
【发布时间】:2019-02-22 23:56:40
【问题描述】:

我在存储String 键和boolean 值的类中有一个Map。然后,我从函数getMap() 返回地图。

public class FacilityMachines {
    private static Map<String, Boolean> map = new HashMap<String, Boolean>();

    public Map getMap(){
         return map;
    }

在下面的课程中,我试图获取该地图,然后将其保存到外部文件,我还在那里实例化FacilityMachines

public class WriteFile {
    FacilityMachines fm = new FacilityMachines();
    private Map<String, Boolean> m = new HashMap<String, Boolean>();

}

WriteFile 中,我正在尝试将地图解析为新的HashMap:

public void saveFacilityInfo() {
    for (Map.Entry<String, Boolean> j: fm.getMap().entrySet()){
            String s = j.getKey();
            boolean b = j.getValue();
            oStream.println(i + ": " + s + " = " + b + ". ");
        }
}

oStream 只是我的PrintWriter 的变量。

以上产生Object cannot be converted to Entry&lt;String, Boolean&gt; 错误。

如果我将saveFacilityInfo 的方法签名更改为saveFacilityInfo(FacilityMachines fm),然后使用fm 变量尝试在for (Map.Entry&lt;String, Boolean&gt; j: fm.getMap().entrySet()) 行获取地图,那么我会在所有函数上得到cannot find symbol Entry 接口:entrySet()getKey()getValue()

在有人问之前,我已经导入了HashMapMap,还尝试只使用import java.util.*; 导入所有内容以防万一。

我还尝试从 WriteFile 扩展 FacilityMachines 并得到相同的结果。

【问题讨论】:

    标签: java dictionary hashmap


    【解决方案1】:

    您需要在 FacilityMachines 类的 getMap() 方法中以正确的类型返回地图

    public class FacilityMachines {
        private static Map<String, Boolean> map = new HashMap<String, Boolean>();
    
        public Map<String, Boolean> getMap(){
            return map;
        }
    }
    

    【讨论】:

    • 有趣,不知道这就是您返回声明类型的地图的方式。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2023-01-18
    • 1970-01-01
    • 1970-01-01
    • 2019-07-07
    • 2021-04-27
    • 2015-07-17
    • 1970-01-01
    • 2017-10-03
    相关资源
    最近更新 更多