I am practicing using HashMap in JAVA from a tutorial. The sample HashMap implementation code fails to compile with the error:
DictionaryPractice.java:57: error: cannot find symbol
shoppingList.replace("Bread", Boolean.FALSE);
symbol: method replace(String,Boolean)
location: variable shoppingList of type Map<String,Boolean>
Here is the code:
import java.util.HashMap;
import java.util.Map;
public class DictionaryPractice {
public static void main(String[] args) {
Map<String, Boolean> shoppingList = new HashMap<String, Boolean>();
// Put some stuff in dictionary
shoppingList.put("Ham", true);
shoppingList.put("Bread", Boolean.TRUE);
shoppingList.put("Oreos", Boolean.TRUE);
shoppingList.put("Eggs", Boolean.FALSE);
shoppingList.put("Sugar", false);
// Retrieve items
System.out.println(shoppingList.get("Ham"));
System.out.println(shoppingList.get("Oreos"));
// Remove things
shoppingList.remove("Eggs");
// Replace values for a certain key
shoppingList.replace("Bread", Boolean.FALSE);
}
}
I have read the JavaDocs on the HashMap class, and confirmed that .replace
is a valid HashMap method to replace a value for a specified key. However, I keep getting the cannot find symbol error
. Your kind help will be appreciated. Sorry for the basic question.
I am using jEdit Text Editor with the Compile plugin installed on a MacOSX Yosemite.
In the above program, "Cannot find symbol" error will occur because “sum” is not declared. In order to solve the error, we need to define “int sum = n1+n2” before using the variable sum.
The “cannot find symbol” error comes up mainly when we try to use a variable that's not defined or declared in our program. When our code compiles, the compiler needs to verify all the identifiers we have. The error “cannot find symbol” means we're referring to something that the compiler doesn't know about.
HashMap<K, V> is a part of Java's collection since Java 1.2. This class is found in java.util package. It provides the basic implementation of the Map interface of Java. It stores the data in (Key, Value) pairs, and you can access them by an index of another type (e.g. an Integer).
The method replace(K,V)
in the Map
interface is a new method introduced in Java 8.
Apparently, you are compiling your code with Java 7 or earlier.
Two possible solutions are:
Replace the replace
with put
. The method replace
is a convenience method used when you don't want the new value to be placed in the map if the key doesn't have some value beforehand, similar to:
if ( shoppingList.contains("Bread") ) {
shoppingList.put("Bread",Boolean.FALSE);
}
In your case, since you put
something for Bread
a few lines earlier, replace
would be unnecessary - you know that Bread
is there. So just use put
directly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With