I have the following TreeMap:
TreeMap<String, Integer> distances = new TreeMap<String, Integer>();
and it contains both strings, “Face” and “Foo”, with appropriate values, such that:
System.out.println(distances);
Yields:
{Face=12, Foo=2}
However, distances.get(Face) returns null, even though distances.get(Foo) properly returns 2. Previously, distances.get(Face) worked, but for some reason, it stopped working. Note I print out the map right before calling get() for both keys, so I haven’t accidentally changed Face’s value to null. Has anyone else ever encountered this problem? Is there anything I can do? I’m having a terrible time simply trying to figure out how to debug this problem.
NOTE: In the real code I’m not actually using Strings, but a different object, so it’s: TreeMap<Object, Integer>. So it’s not simply a confusion of variable names vs. literal strings.
SECOND NOTE: I also feel pretty confident about my implementations of hashcode() and equals() for the object I’m using. (Also, if my implementations weren’t correct, wouldn’t it not work from the beginning? Instead of stopping to work randomly?)
In response to your note: everyone is asking if you’ve overridden
equals()andhashcode()properly — which is important, yes. But this is aTreeMap, which means you also have to care about comparisons — whether you’re usingComparableobjects or an externalComparator, you need to make sure that your comparisons are consistent (are your objects mutable?) and that they’re consistent with yourequals()method.Incidentally, when you said in your original question that you were using
Stringobjects, you did yourself a disservice — Strings are immutable and their comparison methods aren’t under consideration here, so the question was fundamentally different; now that we know your own code is involved, the field of possible solutions is wider.