有一个HashMap
HashMap aircraftHandling = new HashMap<String, HashMap<Double, Integer>>();此HashMap包含以下条目:
HashMap<"M", HashMap<1.22, 200>>();
HashMap<"M", HashMap<5.62, 300>>();
HashMap<"L", HashMap<10.11, 900>>();我需要获取键"M“的条目,即HashMap<1.22, 200>和HashMap<5.62, 300>。我通过以下方式完成此操作:
HashMap lines = (HashMap<Double, Integer>) aircraftHandling.get("M");问题是如何将Double和Integer,即(1.22200)和(5.62300)放入两个独立的变量中?
for (int i=0; i<lines.size(); i++)
{
//doubleValue = [i]???
//integerValue = [i]???
}发布于 2013-06-21 16:27:16
这就是通过迭代键集来提取HashMap的键值对的方法
Iterator<Double> it= lines.keySet().iterator();
while (it.hasNext()) {
Double key= it.next();
Integer value= lines.get(key);
}顺便说一句,我不知道这是一个错误,还是只是一个糟糕的数据表示:
HashMap<"M", HashMap<1.22, 200>>();
HashMap<"M", HashMap<5.62, 300>>();但如果它看起来是这样的,这是不可能的。对于单个键,Map可以有一个值!这意味着,如果您为某个键"M"设置了一些值,然后对同一个键再次执行此操作,则后者将覆盖以前的值。你应该做的是:
//get the inner map for "M"
HashMap<Double, Integer> innerMap= aircraftHandling.get("M");
if (innerMap == null) {
//if it does not exist instantiate it
innerMap= new HashMap<Double, Integer>();
aircraftHandling.put("M", innerMap);
}现在,在innerMap中添加其他值,例如:
innerMap.put(1.22, 200);
innerMap.put(5.62, 300); 发布于 2013-06-21 16:32:05
您可以使用增强的for循环来读取元素:
for (Map.Entry<Double, Integer> entry : lines.entrySet()) {
Double key = entry.getKey();
Integer value = entry.getValue();
}此HashMap包含以下条目:
HashMap<"M", HashMap<1.22, 200>>();
HashMap<"M", HashMap<5.62, 300>>();
HashMap<"L", HashMap<10.11, 900>>();我需要获取键"M“的条目,即HashMap<1.22,200>和HashMap<5.62,300>。我通过以下方式完成此操作:
不考虑所使用的语法,因为键是String,所以当您第二次尝试使用Map 中已存在的String键put() Map中的值时,新值将覆盖旧值。
发布于 2013-06-21 16:30:30
试试这条路吧
Map<Double, Integer> lines = (HashMap<Double, Integer>) aircraftHandling.get("M");
// ^add this generic types here so you wont have to cast them later with getters
for (Map.Entry<Double, Integer> entry:lines.entrySet()){
Double key = entry.getKey();
Integer value = entry.getValue();
}https://stackoverflow.com/questions/17230673
复制相似问题