0

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?

4

4 に答える 4

4

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()
于 2013-01-09T13:08:29.720 に答える
2

You are aware that you cannot alter a key once it is added and it's concrete type shouldn't matter(or be used ideally)

final Map<List<String>,String> mymap = new TreeMap<>(comparator);
for (Map.Entry<List<String>, String> entry : mymap.entrySet()) {

}
于 2013-01-09T13:15:03.507 に答える
1

try

    Iterator<Entry<ArrayList<String>, String>> iter = mymap.entrySet().iterator();
    while(iter.hasNext()) {
        Entry<ArrayList<String>, String> entry = iter.next();
    }
于 2013-01-09T13:11:16.367 に答える
1

You can use a for-each loop to iterate through a map:

for(Map.Entry<List<String>,String> entry : mymap.entrySet()) {
    List<String> key = entry.getKey();
    String value = entry.getValue();

    // Do something useful with the key and value
}

Or you can just loop over the keys using mymap.keySet() or the values mymap.calues().

于 2013-01-09T13:14:48.507 に答える