Casting HashMap Key Iterator to List Iterator
I need to access the key elements of a HashMap like a linked list with prev and curr pointers in order to do some comparisons. I assumed the HashMap Key Iterator for the List Iterator accesses the current as well as the 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 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 a way that I can inject Iterator HashMap Key into List Iterator to solve my purpose. Any help would be appreciated.
Thank,
Somnath
source to share
iterator
adj.keySet()
cannot be sent to ListIterator
because its keyset ( returned by the methodkeySet()
) is not list
, but a Set
. Thus, it has no order.
You can try using LinkedHashMap
for this purpose or create a new instance list
from keySet
like this
List<Node> nodes = new ArrayList<Node>(adj.keySet());
and then perform the required manipulations.
source to share