13.3 Implement an ISBN cache: question regarding code

#1

Hello,
in question 13.3, “Implement an ISBN cache”, the following method for inserting a new ISBN is given:

 public Integer insert(Integer key, Integer value) {
    // We add the value for key only if key is not present - we don't update
    // existing values.
    Integer currentValue = isbnToPrice.get(key);
    if (!isbnToPrice.containsKey(key)) {
      isbnToPrice.put(key, value);
      return currentValue;
    } else {
      return null;
    }
  }

I’m confused about the returned values. We are first getting the value for the key passed as parameter. If this key didn’t exist in the isbnToPrice HashMap, it will return null. After that, we check whether the key exists. If it doesn’t, we put in the key and return the “currentValue”, which will be null due to the condition. We would therefore return null in both cases. It is not clear from the text what the return value is supposed to mean, and the tests on github don’t check the return value of this method.

Edit: after checking the documentation of the HashMap “put”, it seems to me that the return values were intended to function in the same way: if we already had a value, return that value. Otherwise, insert and return null. However, the two return values are then the wrong way around.

0 Likes

#2

Hey @DFischer,

We identified this problem as well, and I think we don’t want to return any value for this function.

The update solution will be like as follows:

   public void insert(Integer key, Integer value) {
     // We add the value for key only if key is not present - we don't update
     // existing values.
     isbnToPrice.get(key);
     if (!isbnToPrice.containsKey(key)) {
       isbnToPrice.put(key, value);
     }
   }
0 Likes