Implement an ISBN cache

#1

Why is isbnToPrice.get(key) in this function? It does not seem to do anything, what am I missing?

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); ***Why is this line here, what does it do?***
   if (!isbnToPrice.containsKey(key)) {
      isbnToPrice.put(key, value);
   }
}
0 Likes

#2

@programmer99
I don’t know where you got that snippet from so I can’t tell if the surrounding code does something that depends on that line.

get has a side-effect where it throws an exception when the key is null, and the map disallows null keys. If the surrounding code depends on this behavior in some way, then the line is relevant as an assertion.

However, in terms of a general solution to the problem, you’re right - I have no such line in my solution.

0 Likes

#3

I can’t figure out how to edit the post but I just want to make clear that isbnToPrice is a LinkedHashMap

LinkedHashMap<Integer,Integer> isbnToPrice;

Sorry for not making that clearer lgtout. When I look at Oracle’s documentation I don’t see LinkedHashMap’s get function throwing any exceptions.

0 Likes

#4

It’s the behavior in the Map interface. https://docs.oracle.com/javase/8/docs/api/java/util/Map.html#get-java.lang.Object-

0 Likes

#5

Hopefully one of the authors could tell us why isbnToPrice.get(key) is in this function

0 Likes

#6

I think it’s safe to say it’s a typo.

0 Likes

#7

This line tries to refresh the last used time of the entry “key”. So it is necessary, you can think it is like “touch” the entry to making sure this entry won’t get deleted if it already existed. Also, since our key is not null, it won’t throw exception in this case.

1 Like

#8

Oh, right. Sorry, @programmer99, I looked at my code but not at the problem, so didn’t realize it was the LRU one. My solution has equivalent behavior, but without the line that you found puzzling.

0 Likes

#9

Thanks for clarifying things Tsung, I really appreciate it!

0 Likes

#10

No worries lgtout I appreciate the help

0 Likes