例子:
@Test public void a16() { String s1="123"; String s2="123"; String s3=new String("123");
System.out.println(s1==s2);
System.out.println(s1==s3);
System.out.println(s1.equals(s3));
}
输出结果:
true
false
true
结论分析:
new String会调用
public String(String original) { this.value = original.value; this.hash = original.hash; }
会生成value和hash值。
而String s1="123";只声明对象,没有创建对象,生成value值。 public static String valueOf(Object obj) { return (obj == null) ? "null" : obj.toString(); }
string 中 equals方法,只比较的是value值。
public boolean equals(Object anObject) { if (this == anObject) { return true; } if (anObject instanceof String) { String anotherString = (String)anObject; int n = value.length; if (n == anotherString.value.length) { char v1[] = value; char v2[] = anotherString.value; int i = 0; while (n-- != 0) { if (v1[i] != v2[i]) return false; i++; } return true; } } return false; }