Search code examples
javadictionaryiteratortreemapsortedmap

Iterator returning error for TreeMap in Java


I have a TreeMap defined like:

final TreeMap<ArrayList<String>,String> mymap = new TreeMap<ArrayList<String>,String>(comparator);

When I try to iterate over it like this:

Iterator iter = (Iterator) mymap.entrySet().iterator();
    while (iter.hasNext()) {
        Map.Entry entry = (Map.Entry) iter.next();
    }

I am getting error message like The method hasNext() is undefined for the type ObjToIntMap.Iterator on the 2nd line and Multiple markers at this line - Map.Entry is a raw type. References to generic type Map.Entry should be parameterized on the 3rd line.

What is the source of this error, and how can I fix it?


Solution

  • Maybe you imported the wrong Iterator class? Are you sure you have imported java.util.Iterator and no other class from an other package that is also named Iterator?

    If you imported the correct Iterator class you can remove the typecast and add the generic type to the iterator:

    Iterator<Map.Entry<ArrayList<String>, String>> iter = mymap.entrySet().iterator()