Java中String比较:==、equals()方法、intern()方法
涉及到String的操作==,equals,intern方法。
*文中出现的代码基于JDK1.8_144版本.
一、 ==比较
1.01 简单类型
{ byte, boolean, short, char, int, long, float, double}
直接比较值。
1.02 引用类型
比较地址值,如果指向同一个地址,返回true。否则返回false。
1.03 String的==比较
可以对比2.01 String中的重写的equals()方法:来看。
废话不多说,直接上代码。
/**
* .
* ==判断引用是否相等.
*/
public static void testEquals2() {
String a = "a";
final String c = "a";
String b = a + "b";
String d = c + "b";
String e = getA() + "b";
String compare = "ab";
System.out.println(b == compare);
System.out.println(d == compare);//编译优化,final能确定,所以指向同一个
System.out.println(e == compare);
}
/**
* 测试用.
* @return “a”
*/
private static String getA() {
return "a";
}
由于编译优化机制,能在编译时确定的直接优化到常量池中。所以相等。如fianl。
-----testEquals2()-----
false
true
false
二、 euqals()比较
Object中的equals()方法 与 == 相同。
2.01 String中的重写的equals()方法:
Compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.
比较他们的字符串值是否相同。
public static void testEquals3() {
String a = "a";
final String c = "a";
String b = a + "b";
String d = c + "b";
String e = getA() + "b";
String compare = "ab";
System.out.println(b.equals(compare));
System.out.println(d.equals(compare));
System.out.println(e.equals(compare));
}
-----testEquals3()-----
true
true
true
毫无疑问相同,我们来看看JDK源码吧:
JDK8源码
public boolean equals(Object var1) {
if (this == var1) {
return true;
} else {
if (var1 instanceof String) {
String var2 = (String)var1;
int var3 = this.value.length;
if (var3 == var2.value.length) {
char[] var4 = this.value;
char[] var5 = var2.value;
for(int var6 = 0; var3-- != 0; ++var6) {
if (var4[var6] != var5[var6]) {
return false;
}
}
return true;
}
}
return false;
}
}
*当然,String也重写了hashCode()方法。
三、 intern方法介绍
Returns a canonical representation for the string object.
A pool of strings, initially empty, is maintained privately by the class String.
When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.
It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true.
All literal strings and string-valued constant expressions are interned. String literals are defined in section 3.10.5 of the The Java™ Language Specification.
intern()方法:
当调用intern方法时,JVM会在常量池中通过equals()方法来匹配是否存在等值的String,
如果存在,则直接返回其地址。否则再新建.
所以,只要值相等,用.intern()==.intern()判断一定相等.
但是intern效率不高.
private static void testIntern() {
String a = "a";
String b = a + "b";
String c = "ab";
String d = new String(b);
System.out.println(b == c);
System.out.println(c == d);
System.out.println(c == d.intern());
System.out.println(b.intern() == d.intern());
}
-----testIntern()-----
false
false
true
true
参考资料:
Java 8 API
< Java特种兵(上册) > 谢宇 ISBN: 9787121239359