Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can I use Strings as keys in a HashMap?

Tags:

java

hashmap

If two Strings 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?

like image 351
Tom Marthenal Avatar asked Feb 23 '12 23:02

Tom Marthenal


4 Answers

HashMap compares objects by calling equals() and hashCode().
String overrides these methods to compare by value.

like image 193
SLaks Avatar answered Oct 26 '22 18:10

SLaks


In general, you can use String objects because HashMap uses equals() and not == to test for key equality.

like image 32
Ted Hopp Avatar answered Oct 26 '22 19:10

Ted Hopp


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.

like image 26
user207421 Avatar answered Oct 26 '22 19:10

user207421


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.)

like image 24
Affe Avatar answered Oct 26 '22 19:10

Affe