Home > Enterprise >  My method need to return a boolean. theres a for loop in the body and an if-else statement within th
My method need to return a boolean. theres a for loop in the body and an if-else statement within th

Time:01-30

public static boolean addPassIfUnique(HashMap<String, EntryPass> entryPassHashMap,EntryPass entryPass) {
    //fill in method
    boolean isThere;
    for (HashMap.Entry<String, EntryPass> entry : entryPassHashMap.entrySet()) {
        if (entry.getValue().equals(entryPass)) {
            isThere = true;
        } else {
        entryPassHashMap.put(entryPass.getName()   entryPass.getId(), entryPass);
            isThere = false;
        }
    }
    return isThere;
}

Im expecting my if-else statements to update the variable "isThere" but when I try returning "isThere" it tells me it hasn't been initialized.

CodePudding user response:

Your isThere variable ONLY gets initialized if the entryPassHashMap.entrySet() contains items. If the entrySet() is empty, then the for loop doesn't run, and thus isThere remains uninitialized.

CodePudding user response:

The method as written, will have uninitialised isThere for empty map - your for loop will not do anything, and your boolean will remain uninitialised.

Think again on what you are doing here - I suggest rethinking and rewriting from scratch.

  • Related