Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting HashMap Key Iterator to List Iterator

I need to access the HashMap key elements much like a linked list with prev and curr pointers to do some comparisons. I typecasted the HashMap Key Iterator to List Iterator to access current as well as previous key elements. Below is the code

HashMap<Node,Double> adj;
ListIterator<Node> li = (ListIterator<Node>) adj.keySet().iterator();

while (li.hasNext()) {
    if (li.hasPrevious()) {
                prev = li.previous();
    } else {
                prev = null;
    }
...
}

But I am getting the below exception

Exception in thread "main" java.lang.ClassCastException: java.util.HashMap$KeyIterator cannot be cast to java.util.ListIterator
at Types$AdjList.makeConnected(Types.java:357)
at Main.main(Main.java:89)

Is there some way that I can typecast a HashMap Key Iterator to List Iterator to solve my purpose. Any help will be appreciated.

Thanks,

Somnath

like image 852
somnathchakrabarti Avatar asked Mar 25 '12 03:03

somnathchakrabarti


People also ask

Can we use list iterator for HashMap?

Example 2: Iterate through HashMap using iterator() In the above example, we are iterating through keys, values, and key/value mappings of the hash map. We have used the iterator() method to iterate over the hashmap. Here, hasNext() - returns true if there is next element in the hashmap.

Can we use ListIterator with map in Java?

It has got both next() and previous() methods to access the next and previous elements from the List. Unfortunately, ListIterator only supports the List interface, you cannot use it to traverse over Map or Set in Java.

How many ways can you iterate a map in Java?

There are generally five ways of iterating over a Map in Java.


1 Answers

The iterator of adj.keySet() cannot be casted to a ListIterator because its keys set (returned by the keySet()) method is not a list, but a Set. Thus it doesn't have an order.

You can try to use LinkedHashMap for this purpose or create a new List instance from the keySet like this

List<Node> nodes = new ArrayList<Node>(adj.keySet());

and then perform the desired manipulations.

like image 183
Eugene Retunsky Avatar answered Sep 30 '22 18:09

Eugene Retunsky