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
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.
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.
There are generally five ways of iterating over a Map in Java.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With