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

+3


source to share


3 answers


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.

+9


source


Try it.



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

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

      

0


source


    public HashMap JsonToMap(JSONObject js,HashMap hm){
         @SuppressWarnings("unchecked")
         Iterator<String> nameItr =  js.keySet().iterator();
         while(nameItr.hasNext()) {
             String name = nameItr.next();
             hm.put(name, js.get(name).toString());
         }
        return hm;
    }

      

0


source







All Articles