简体   繁体   中英

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. 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. 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<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<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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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