简体   繁体   中英

for loop not iterating through my hashmap's key set

I have a HashMap that is in this format:

HashMap<List<String>, List<String[]>>

this hashmap is already populated and this is part of the results returned when i view the keyset:

[[124, 1], [136, 2], [136, 1], [257, 1], [502A, 1], [269, 1], [111, 1], [232, 1], [123, 1], [93, 1], [81, 1], [93, 2], [6N, 1]]

(not full because the whole thing is too long)

I am trying to to a for loop to iterate through all my keyset using this code:

for(List<String> key : hashmap.keySet()){
    if(key.get(0) == input){
            if(key.get(1) == "1"/*second part of key*/){
                dir1.add(hashmap.get(key).get(0)[1]);
            }
            else if(key.get(1) == "2"/*second part of key*/){
                dir2.add(hashmap.get(key).get(0)[1]);
            }
        }
}

However, when I set a breakpoint and debug the project, I realized that the for loop only loop once. What am I doing wrong?

You should use a proper class for the keys, not List<String>

You should compare Strings using .equals. ie "1".equals(key.get(1))

The actual foreach looks fine so if it isn't looping then either something is breaking/exceptioning you out of the loop or your data structure actually contains only one item. It's also entirely possible it is looping more than once but due to the bad comparisons on the if statements you think it isn't.

I'd start by checking your Map really contains multiple entries. The way you have it set up at the moment with maps of lists of lists of arrays is just asking for a confusing mess.

ok sorry guys the problem is with my netbeans or my computer but i restarted my computer and everything works now. Thanks everyone who tried to help

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