While using 2 different HashMaps, i'm able to create a keySet with the first but not the second

StackOverflow https://stackoverflow.com/questions/20279426

  •  06-08-2022
  •  | 
  •  

Question

I'm working with 2 different HashMaps in a class, and when I call the keySet() method with the first (the getExitString() method), it works fine, but when I call it with the second (the getLockedDoors() method), I get the "cannot find symbol - method keySet()" error. How can I fix this? Thanks! The relevant code is below.

import java.util.HashMap;
import java.util.Set;

public class Room 
{
private HashMap<String, Room> exits;    
private HashMap<String, LockedDoor> lockedDoors;

public String getExitString() {
    String exitReturn = "";
    Set<String> exitSet = exits.keySet();
    for (String eachExit : exitSet) {
        exitReturn = exitReturn + eachExit + " ";
    }
    return exitReturn;
}

public String getLockedDoorString() {
    String lockedDoors = "";
    Set<String> doorSet = lockedDoors.keySet();
    for (String door : doorSet) {
        lockedDoors = lockedDoors + door + " ";
    }
    return lockedDoors;
}
Was it helpful?

Solution

At the failing line, lockdoors resolves to a String and not a HashSet expression.

This is because the local variable shadows the member variable with the same name.

String lockedDoors = "";                     // shadowed here
Set<String> doorSet = lockedDoors.keySet();  // and String.keySet() is bogus

Solution: You can either use a different name for your local variable (recommended, IMO) or use the this keyword to reference the instance level variable (a concept often required). Here's a sample.

String lockedDoors = "";
Set<String> doorSet = this.lockedDoors.keySet();

OTHER TIPS

Your local variable name and the name for the HashMap is same hence giving error

String lockedDoors = "";

lockedDoors is String object, which has same name as your HashMap lockedDoors.

And String class does not have the method keySet :)

String lockedDoors = "";
Set<String> doorSet = lockedDoors.keySet();

The main problem with your code is above two lines because "Already you have declared lockedDoors as a hashmap object and you have declared lockedDoors as string object in method getLockedDoorString()", In this case lockedDoors variable always reference to the local string lockedDoors object. That's why it's throwing error. please use different name or declare your variable on top.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top