I am running into this weird issue where I am iterating over a list of responses. when I try to get the answer from each response by the question, most of them get the answer correctly except one where getting the answer from the hashmap gives null. I have ran the debug mode in eclipse, and compared the question that I try to get its value from the hashmap getAnswerMap() with the one inside that hashmap and both seem to be exactly the same, but I still get null.
for (SurveyResponse response : responses) {
MultipleChoiceAnswer answer = (MultipleChoiceAnswer) response.getAnswerMap().get(question);
....
....
}
Then, I thought it is a hashcode issue, so I added another ugly line of code to check hashcodes, and they actually have the same hashcode and the additional following line worked and did set answer correctly.
for (SurveyResponse response : responses) {
MultipleChoiceAnswer answer = (MultipleChoiceAnswer) response.getAnswerMap().get(question);
for (Entry entry: response.getAnswerMap().entrySet()) {
if (entry.getKey().hashCode() == question.hashCode()) answer = (MultipleChoiceAnswer) entry.getValue();
....
....
}
However, this is very ugly and I would really like to get the answer correctly from the hashmap. Any suggestions?
UPDATE:
calling both hashCode() and equals() method on both objects shows that both have equal hashcodes and equals() returns true. I suspect that as one of the answers down indicate, the problem might be that the question was inserted with a different hashcode when it was inserted in the hashmap. Therefore, calling the get method in question returns null because the object I am trying to get does not have the same hashcode as the old one. Extremely helpful answers guys!
One thing to watch out for: Make sure the class you’re using as a key is immutable — otherwise, a key will hash to one thing when you put it in, but something different when you take it out.
Edit: It doesn’t have to be immutable, but it has to be true that it can only be changed in a way that doesn’t change the hashcode. Making the entire object immutable is the simplest way to do that, but it’s not the only way.