If two String
s that are the same are not actually identical, then why can I use strings as keys in a HashMap
without using the same String
object?
String s1 = "Test";
String s2 = "Test";
System.out.println(s1 == s2); // should be false
System.out.println(s1.equals(s2)); // should be true
HashMap<String, String> map = new HashMap();
map.put(s1, "foo");
System.out.println(map.get(s2)); // should be "foo"--but why?
Does HashMap
have some special behavior for String
objects? If not, why can two "different" strings be used to put and to get values from a hash?
HashMap
compares objects by calling equals()
and hashCode()
.String
overrides these methods to compare by value.
In general, you can use String objects because HashMap uses equals()
and not ==
to test for key equality.
If two Strings that are the same are not actually equal
But they are. They are equal under the equals() method, and that is the technique specified for equality testing in the Map
interface.
System.out.println(s1 == s2); // should be false
But it isn't false! Both refer to the same string because of constant pooling by the compiler.
When the HashMap
compares the key internally, it uses the equals()
method, not ==
. So object equality is fine for a key match, reference equality is not required if equals()
is overridden (as in the case of java.lang.String
.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With