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
The
iteratorofadj.keySet()cannot be casted to aListIteratorbecause its keys set (returned by thekeySet()) method is not alist, but aSet. Thus it doesn’t have an order.You can try to use
LinkedHashMapfor this purpose or create a newListinstance from thekeySetlike thisand then perform the desired manipulations.