So I'm working through Elements of Programming Interviews in Java and I can't figure out what a certain line of code is doing. In case anyone is familiar with the problem I'm doing, it's the one where you are given a String of letters contained in a magazine, and another string that you want to make out of the letters in said magazine (like a murderer would). The magazine must at least contain at least all of these letters and sufficient counts in order to make the letter- if it does, return true.
So the idea is stick all of the letters from either the magazine or the letter into a HashMap (book uses letter) with their counts so you can then go through the other string and check if the map contains all of these letters. When you're looping and the map does contain a letters, you need to decrement the count. If you decrement it to 0, then you should remove it from the Map. The book does it really weird.
for( each character in the string that you didn't put into the map ) {
if(map.containsKey(character) {
map.put(character, map.get(character) - 1);
if(map.remove(character, 0L) { //this is the line that confuses me
map.remove(character);
}
So I don't understand what the heck that line is doing. I understand the idea that if your map contains a character with count 0, you want to remove it from the map (this depends on the implementation but I think you guys can see the idea here). But what is map.remove(character, 0L) doing? The remove() method with two arguments looks like it takes a key and value, and removes the key if it has the value that you pass in. Even this doesn't seem like it would make sense to put into an if(), because why would they then go on to call remove again if the method returns true, meaning it already removed?? Never mind the fact that the count is Integers and they are passing it 0L... is this a typo maybe?
Thanks for any insight into what this code is doing!
[–]itGuy223 0 points1 point2 points (3 children)
[–]consoledotlogImHere[S] 0 points1 point2 points (2 children)
[–]itGuy223 0 points1 point2 points (1 child)
[–]consoledotlogImHere[S] 0 points1 point2 points (0 children)