0
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?

Chris Martin
  • 30,334
  • 10
  • 78
  • 137
Redowl
  • 23
  • 4

1 Answers1

3

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.

drew moore
  • 31,565
  • 17
  • 75
  • 112
  • Is this something I could have found out just by reading the documentation? – Redowl Sep 23 '14 at 02:03
  • Yes it is, but generics are a fairly large concept to wrap your head around, I recommend you start by looking at the tutorial I linked to. – drew moore Sep 23 '14 at 02:14
  • It's probably also worth mentioning that this is the "older-style" iteration which doesn't tend to be used as much anymore vs. the newer *for-each* iteration (or even newer `Iterable.forEach` in Java 8) [More Info](http://stackoverflow.com/questions/16635398/java-8-iterable-foreach-vs-f). – khampson Sep 23 '14 at 02:35