如何通过hashMap调用Iterator

时间:2010-08-14 09:53:22

标签: java iterator hashmap

我需要查看我的hashMap键和值,以检查它是否正常工作。但我收到以下行的错误:

Iterator iterator =  myHashMap.keySet().iterator();
    Flows flows = new Flows();
    while(iterator.hasNext()){
        Object key = iterator.next();
        Object value = myHashMap.get(key); // <--
        //here is the error.  suspicious call to java.util.Map.get 
        //expected type Flows, actual type object

        System.out.println(key+" "+value);
    }

我的键是Flow的类型,我的值是FlowsStatics。

2 个答案:

答案 0 :(得分:4)

您是否使用Generic类型声明了myHashMap:例如HashMap&lt; Flows,FlowStatics&gt; ?

如果是这样,你应该在整个过程中使用泛型:

Iterator<Flows> iterator =  myHashMap.keySet().iterator();
while(iterator.hasNext()){
    Flows key = iterator.next();
    FlowStatics value = myHashMap.get(key); // <--

甚至:

for(Flows key: myHashMap.keySet().iterator()){
    FlowStatics value = myHashMap.get(key);

甚至:

for(Map.Entry<Flows, FlowStatics> entry: myHashMap.entrySet().iterator()){
    Flows key = entry.getKey();
    FlowStatics value = entry.getValue();

答案 1 :(得分:3)

如果你将Map声明为Map<Flows, FlowsStatics>,你的迭代器会自动返回类Flow的对象,你真的应该这样做:

while(iterator.hasNext()){
    Flows key = iterator.next();
    FlowsStatics value = myHashMap.get(key);