如果两个相同的字符串实际上不是相同的,那么我为什么可以在HashMap中使用字符串作为键,而不使用相同的String对象呢?
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?
HashMap
对 String
对象有特殊的行为吗?如果没有,为什么两个“不同”的字符串可以用于将值放入哈希表中并从哈希表中获取值?
s1 == s2
将为true
。 - Ted Hopp.equals()
来比较String
是标准做法呢? - Tom Marthenal