字符串比较
-
通过字面量赋值创建字符串(如:String s=”hi”),会先在常量池中查找是否存在相同的字符串,若存在,则直接指向该字符串;若不存在,则在常量池中生成一个字符串,再将引用指向该字符串。
-
通过new String创建字符串,在堆上创建一个,同时在常量池创建一个值相同的对象,但是这两个对象互不相干,如果常量池里已经有了同样的值的对象,只会在堆里新建对象
-
常量字符串和变量拼接时或者变量与变量拼接时会调用stringBuilder.append()在堆上创建新的对象,而不会同时在常量池里新建对象
String s = new String("a") + new String("b");
约等于
StringBuilder sb = new StringBuilder(); sb.append("a").append("b"); // toString()只会在堆上创建对象("ab"),new String("ab") 会在堆上和常量池都创建 String s = sb.toString();
-
调用字符串对象的 intern() 方法时,intern方法会先去常量池找,如果存在,指向常量池中的,如果不存在,在常量池中生成一个对原字符串的引用
-
字面量+字面量在编译期间就优化成了常量
String s = new String("a") + new String("b"); String intern = s.intern(); System.out.println(s == intern);// true
String str1 = "哈哈"; String str2 = str1 + "呵呵"; String str3 = "哈哈呵呵"; System.out.println(str2 == str3);// false
String s1 = "abc"; String s2 = "a"; String s3 = "bc"; String s4 = s2 + s3; System.out.println(s1 == s4);// false
注意这个与上一个对比
String s1 = "abc"; final String s2 = "a"; final String s3 = "bc"; String s4 = s2 + s3; // 因为final变量在编译后会直接替换成对应的值,所以实际上等于s4=”a”+”bc”,而这种情况下,编译器会直接合并为s4=”abc” System.out.println(s1 == s4);//true
String s = new String("abc"); String s1 = "abc"; String s2 = new String("abc"); System.out.println(s == s1.intern());// false System.out.println(s == s2.intern());// false System.out.println(s1 == s2.intern());// true
String a = "a"; String b = "b"; String ab = a+b; String ab2 = a+b; String Iab = ab.intern(); String Iab2 = ab2.intern(); // ab与ab2都在堆里 System.out.println(ab==ab2);// false // 常量池中没有"ab"即String ab = a+b;也等价于sb.append("a").append("b"); System.out.println(Iab==ab);// true System.out.println(Iab2==ab);// true
你到底懂了吗
public class StringDemo {public static void main(String[] args) {m7();}private static void m1() {String a = "a";String b = "b";String s = a + b;String intern = s.intern();System.out.println(s == intern);}private static void m2() {String s = new String("a") + new String("b");String intern = s.intern();System.out.println(s == intern);}private static void m3() {String a = "a";String ab1 = a + "b";String ab2 = "ab";System.out.println(ab1 == ab2);}private static void m4() {String a = "a";String b = "b";String ab1 = a + b;String ab2 = "ab";System.out.println(ab1 == ab2);}private static void m5() {final String a = "a";String ab1 = a + "b";String ab2 = "ab";System.out.println(ab1 == ab2);}private static void m6() {String ab1 = "ab";String ab2 = new String("ab");String ab3 = new String("ab");System.out.println(ab2 == ab1.intern());System.out.println(ab2 == ab3.intern());System.out.println(ab2.intern() == ab3.intern());System.out.println(ab1 == ab3.intern());}private static void m7() {String a = "a";String b = "b";String ab1 = a + b;String ab2 = a + b;System.out.println(ab1 == ab2);System.out.println(ab1 == ab1.intern());System.out.println(ab2 == ab2.intern());System.out.println(ab1 == ab2.intern());System.out.println(ab1.intern() == ab2.intern());}}