【发布时间】:2015-02-13 15:39:17
【问题描述】:
我有一个包含四个答案的 Hashmap。我有前 2 个问题。我就是这样做的
// Awnsers question 1
antwoorden1.put("Hypertext Preprocessor", true);
antwoorden1.put("Hypertext PHPprocessor", false);
antwoorden1.put("Hypertext processor", false);
antwoorden1.put("Preprocessor PHP", false);
// Awnsers question 2
antwoorden2.put("Model view config", false);
antwoorden2.put("Model view connect", false);
antwoorden2.put("Model view controllers", false);
antwoorden2.put("Model view controller", true);
现在我需要访问所有这些信息,所以我要做的就是将两个 HashMap 添加到一个 ArrayList
// Add the Hashmaps to the arrayList
alleAntwoorden.add(antwoorden1);
alleAntwoorden.add(antwoorden2);
但是如何循环遍历 ArrayList 以从 HashMap 中获取键和值?这是我已经尝试过的。
for(int i = 0; i < alleAntwoorden.size(); i++)
{
for (Map.Entry<String, Boolean> entry : alleAntwoorden.get(i).entrySet())
{
String key = entry.getKey();
Object value = entry.getValue();
// ...
}
}
但我总是收到以下消息:不兼容的类型
Antwoorden1、anttwoorden2 和 alleAntwoorden 定义为:
private ArrayList<HashMap> alleAntwoorden;
private HashMap<String, Boolean> antwoorden1, antwoorden2;
【问题讨论】:
-
boolean value = entry.getValue();而不是Object。alleAntwoorden应该是List<Map<String, Boolean>>类型。 -
antwoorden1、antwoorden2和alleAntwoorden是如何定义的? -
能否提供详细的错误信息?
-
在这种情况下,我不确定 HashMap 是否实用。存储包含字符串和布尔值的 4 个答案的 ArrayList 可能更合适。
-
@user3704388 你能说一下,为什么要迭代所有答案?我觉得你的设计可能有问题,
List<Map<String,Boolean>>不方便。可以考虑 Compass 的AnswerType 方法。
标签: java list loops arraylist hashmap