I've been working on a drunk walker coding problem (custom user classes, etc.), and I'm going insane trying to fix this small issue.
I messed around with the code (to no avail), and so with no hope in sight, I decided to get an outside opinion.
The code I used for adding into the hashmap is like this:
if (hashMap.containsKey(key) == false) {
hashMap.put(key, 1);
}
else {
hashMap.put(key, value + 1);
}
In theory, this should be completely fine. If the key is not saved in map, it is added to the map with a value of 1. If the key is actually there in the map, then the value is incremented by one. The key is just an instance of a custom class that takes two integer variables. It is being constantly updated.
At the end of the program, if I display entries in the hashmap with values greater than 1, it should look something like this:
Visited Intersection [avenue=8, street=42] 3 times!
Visited Intersection [avenue=8, street=63] 2 times!
But when I observed what the hashmap looked like with each function call, it looked like this:
Hash Map: {Intersection [avenue=6, street=22]=1}
Hash Map: {Intersection [avenue=6, street=23]=1, Intersection
[avenue=6, street=23]=1}
Hash Map: {Intersection [avenue=6, street=22]=2, Intersection
[avenue=6, street=22]=1}
Hash Map: {Intersection [avenue=5, street=22]=2, Intersection
[avenue=5, street=22]=1, Intersection [avenue=5, street=22]=1}
Hash Map: {Intersection [avenue=6, street=22]=3, Intersection
[avenue=6, street=22]=1, Intersection [avenue=6, street=22]=1}
...
Every entry in the hashmap was being overwritten, and the end product was this:
Visited Intersection [avenue=8, street=20] 3 times!
Visited Intersection [avenue=8, street=20] 2 times!
Visited Intersection [avenue=8, street=20] 2 times!
Visited Intersection [avenue=8, street=20] 2 times!
...
Originally I thought the code for adding into the hashmap was incorrect, since every key was being overwritten and only the last updated one is displayed, but now I think it has to do with the actual updating of the key.
Penny for your thoughts? Sorry if it's a bit vague.