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?
HashMapcompares objects by callingequals()andhashCode().Stringoverrides these methods to compare by value.