Reputation: 23
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?
Upvotes: 0
Views: 61
Reputation: 32690
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.
Upvotes: 3