如何检查HashMap中的唯一变量?

时间:2012-12-14 17:42:28

标签: java

我编写了代码来在HashMap中查找唯一变量,但它似乎不起作用?我希望能够打印每种香肠类型的频率。

    if(sausagesEaten.isEmpty()) { //if the HashMap is empty
        System.out.println("No sausages have been eaten");
        System.out.println("======================================================="); ; 
    }
    else{
        HashMap<ArrayList, String> sausagesEaten = new HashMap<ArrayList, String>();
        for (String key : sausagesEaten) {
              System.out.println(key + ": " + Collections.frequency(saustype, key));
        }
        System.out.println(" ");
    }

2 个答案:

答案 0 :(得分:0)

假设您的代码中已经有一个名为sausagesEaten的填充HashMap更高。

变化:

 if(sausagesEaten.isEmpty()) { //if the HashMap is empty
    System.out.println("No sausages have been eaten");
    System.out.println("======================================================="); ; 
}
else{
    HashMap<ArrayList, String> sausagesEaten = new HashMap<ArrayList, String>();
    for (String key : sausagesEaten) {
          System.out.println(key + ": " + Collections.frequency(saustype, key));
    }
    System.out.println(" ");
}

要:

 if(sausagesEaten.isEmpty()) { //if the HashMap is empty
    System.out.println("No sausages have been eaten");
    System.out.println("======================================================="); ; 
}
else{
    for (String key : sausagesEaten) {
          System.out.println(key + ": " + Collections.frequency(saustype, key));
    }
    System.out.println(" ");
}

通过重新声明变量,它是本地范围并自动清空。

编辑:为正确的迭代添加了更改。

Iterator it = sausagesEaten.entrySet().iterator();
while (it.hasNext()) {
    Map.Entry pairs = (Map.Entry)it.next();
    System.out.println(pairs.getKey() + " = " + pairs.getValue());
}

答案 1 :(得分:0)

您无法直接在HashMap上进行迭代。以下是可以做的事情:

Map<K,V> map = new HashMap<K,V>(); // whatever K and V are

for (K key : map.keySet())
{
    // iterates over all the keys in random order
}

for (V value : map.values())
{
    // iterates over all the values, in random order
}

此外,使用诸如ArrayList之类的可变对象作为地图的关键字是非常不正统和危险的,如

HashMap<ArrayList, String> sausagesEaten = new HashMap<ArrayList, String>();

将它放入地图后,如果以任何方式修改其内容,您将破坏地图并可能或可能无法检索它。我想你的意思是

HashMap<String, ArrayList> sausagesEaten = new HashMap<String, ArrayList>();

此外,在您的代码中,您在sausagesEaten子句中重新声明else,隐藏同名的成员变量。