Question about .get method

This is my first time working with hashmaps so bear with me. My code works but I have a question about the process taking place. On line 7 below, why does library.get(book) evaluate a boolean value? Why would it not retrieve the string value - that being the name of the book. It looks like “book” is declared as a string value and then checked to be a boolean value. I would greatly appreciate a beginner’s explanation for this!

public void getFinishedBooks (HashMap<String, Boolean> library){
    	if (library.size() < 1){
      System.out.println("It's empty.");
    	else {
        for (String book : library.keySet()){  
          if (library.get(book) == true){
            System.out.println("This book has been completed: " + book);

Hey there.

The trick is to look in the foreach loop parameters.

for (String book : library.keySet()){  

We have two things going on here.

The keySet() method is a method that belongs to all HashMap objects. It retrieves all of the keys in the library HashMap. In this case the keys are the names of the books.

String book
This is a placeholder variable. It holds the key(book name) that we are going to be searching for.

Essentially this for loop is saying.
Use book as a placeholder for each key that we find in the library HashMap

Now the if statement library.get(book) == true) should make a little more sense to you.
This is because we’re getting the value associated with our book/key placeholder. And since the value is going to be of boolean datatype this is how we can use it to get a true/false condition result back.

Hope that makes sense. Let me know if it doesn’t.

This makes sense. Thanks for your help.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.