简体   繁体   中英

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

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.

    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;
    }

Try this..

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM