问题
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?
回答1:
HashMap compares objects by calling equals() and hashCode().String overrides these methods to compare by value.
回答2:
In general, you can use String objects because HashMap uses equals() and not == to test for key equality.
回答3:
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.
回答4:
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.)
回答5:
System.out.println(s1 == s2); // should be false
It should not. Java compiler may optimize and point two strings to the same location.
Update
public class Test {
public static void main(String... args) {
String s1 = "abc";
String s2 = "abc";
System.out.println(s1 == s2);
}
}
Output
javac Test.java
java Test
> true
回答6:
we should really go back to the basic first.
computer science fundamental:
== compares memory address(reference)
.equals compares value stored in the memory address
java basic. there is only one copy of string object across entire jvm
来源:https://stackoverflow.com/questions/9423188/why-can-i-use-strings-as-keys-in-a-hashmap