繁体   English   中英

遍历arraylist的hashmap

[英]Iterating over a hashmap of arraylist

Set set = hm.entrySet();
Iterator i = set.iterator();

while (i.hasNext()) {
    Map.Entry me = (Map.Entry)i.next();

    // me.getValue should point to an arraylist
    Iterator<Student> it = (me.getValue()).iterator();

    while (it.hasNext()) { 
        // some code
    }
}

好的,我尝试遍历Arraylist,由于某种原因它不起作用,编译器告诉我找不到符号。 我知道me.getValue()应该指向一个对象,在这种情况下,键/值对的值部分是Arraylist。 那怎么了

当你做

 Map.Entry me = (Map.Entry)i.next();

您正在创建Map.Entry的无类型实例,就像这样做

 Map.Entry<Object, Object> me = ...

然后,当您尝试做

Iterator<Student> it = (me.getValue()).iterator(); 

这相当于尝试做

ArrayList<Object> objects;
Strudent s = objects.get(0);

显然,您无法做到。 相反,您需要使用适当的类型实例化Map.Entry对象:

 Map.Entry<YourKeyType, ArrayList<Student>> me =  
       (Map.Entry<YourKeyType, ArrayList<Student>>) i.next();

请注意,通过将迭代Iterator<YourKeyType, ArrayList<Student>>而不是将其声明为原始类型Iterator<YourKeyType, ArrayList<Student>> ,并充分利用泛型类型的安全性

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM