简体   繁体   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
    }
}

Ok, I tried iterating over an Arraylist and for some reason it doesn't work, the compiler tells me that it cannot find the symbol. 好的,我尝试遍历Arraylist,由于某种原因它不起作用,编译器告诉我找不到符号。 I know that me.getValue() should point to an object and in this case the value part of the key/value pair is an Arraylist. 我知道me.getValue()应该指向一个对象,在这种情况下,键/值对的值部分是Arraylist。 So, what's wrong? 那怎么了

When you do 当你做

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

you're creating an untyped instance of Map.Entry, which is like doing 您正在创建Map.Entry的无类型实例,就像这样做

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

Then, when you try to do 然后,当您尝试做

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

this is the equivalent of trying to do 这相当于尝试做

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

which, obviously, you cannot do. 显然,您无法做到。 Instead, you need to instantiate your Map.Entry object with the appropriate type: 相反,您需要使用适当的类型实例化Map.Entry对象:

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

Note that you can avoid the cast there, and take full advantage of generic type safety , by making your iterator an Iterator<YourKeyType, ArrayList<Student>> rather than declaring it as a raw type. 请注意,通过将迭代Iterator<YourKeyType, ArrayList<Student>>而不是将其声明为原始类型Iterator<YourKeyType, ArrayList<Student>> ,并充分利用泛型类型的安全性

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

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