1
  • I have two HashMap, that both have keys of Characters and values of Integers.
  • I'd like to compare two single entries from the two HashMap, as shown below:
Map<Character, Integer> tmap = new HashMap<>();
Map<Character, Integer> smap = new HashMap<>();

// initialization not shown here.

if (smap.get('a') == tmap.get('a')) {do something...}
  • For some reason, the if statement always returns false here, even though I made sure in these two HashMap 'a' both have the same value.
  • If I use smap.get('a').equals(tmap.get('a')) instead, it works totally fine.
  • At first I thought it has something to do with collision handling in HashMap. I know in Java, after reaching a certain threshold of collision, the collision will be stored using BST instead of LinkedList. But both HashMap only have 26 keys, that can not be the reason.
  • I also understand that == checks if both objects point to the same memory location and .equals() compares the values in the objects. With all these information, I still can not figure out a good explanation for the bug.
  • The detailed code can be found here: https://leetcode.com/problems/minimum-window-substring/discuss/1435814/Help!-Can-not-figure-out-one-small-bug.
  • I really appreciate it if anyone can help me with this question!
Ivan Z
  • 31
  • 1
  • 4

1 Answers1

3

I think the difference between .equals() and == operator that you're looking for is that the == operator is used to check a reference or memory address of the objects whether they point to the same location or not, and the equals() method is used to compare the contents of the object e.g. in case of comparing String its characters, in case of Integer it's their numeric values, etc.

So, I believe since you have two different HashMaps, although the value is the same, they are located in different addresses, therefore == is turning up a false.

zakpruitt
  • 162
  • 2
  • 11