jdk1.9的String结构示例:
public final class String implements java.io.Serializable, Comparable,CharSequence {
@Stable
private final byte[] value;
}
简称:不可变性。
示例代码:
/*** String的基本使用:体现String的不可变性*/
public class StringTest1 {@Testpublic void test1() {String s1 = "abc";//字面量定义的方式,"abc"存储在字符串常量池中String s2 = "abc";//s1,s2指向同一个abcs1 = "hello";//s1指向字符串常量池新开辟了的hello,不影响原有的abcSystem.out.println(s1 == s2);//判断地址:true --> falseSystem.out.println(s1);//helloSystem.out.println(s2);//abc}@Testpublic void test2() {String s1 = "abc";String s2 = "abc";s2 += "def";System.out.println(s2);//abcdefSystem.out.println(s1);//abc}@Testpublic void test3() {String s1 = "abc";String s2 = s1.replace('a', 'm');System.out.println(s1);//abcSystem.out.println(s2);//mbc}
}
测试代码:
class Memory {public static void main(String[] args) {//line 1int i = 1;//line 2Object obj = new Object();//line 3Memory mem = new Memory();//line 4mem.foo(obj);//line 5}//line 9private void foo(Object param) {//line 6String str = param.toString();//line 7System.out.println(str);}//line 8
}
显示的调用toString()方法在字符串常量池当中生成调用者对应的字符串,并且返回常量池当中的地址。
x
示例代码1:
@Testpublic void test1(){String s1 = "a" + "b" + "c";//编译期优化:等同于"abc"String s2 = "abc"; //"abc"一定是放在字符串常量池中,将此地址赋给s2/** 最终.java编译成.class,再执行.class* String s1 = "abc";* String s2 = "abc"*/System.out.println(s1 == s2); //trueSystem.out.println(s1.equals(s2)); //true}@Testpublic void test2(){String s1 = "javaEE";String s2 = "hadoop";String s3 = "javaEEhadoop";String s4 = "javaEE" + "hadoop";//编译期优化//如果拼接符号的前后出现了变量,则相当于在堆空间中new String(),具体的内容为拼接的结果:javaEEhadoopString s5 = s1 + "hadoop";String s6 = "javaEE" + s2;String s7 = s1 + s2;System.out.println(s3 == s4);//trueSystem.out.println(s3 == s5);//falseSystem.out.println(s3 == s6);//falseSystem.out.println(s3 == s7);//falseSystem.out.println(s5 == s6);//falseSystem.out.println(s5 == s7);//falseSystem.out.println(s6 == s7);//false//intern():判断字符串常量池中是否存在javaEEhadoop值,如果存在,则返回常量池中javaEEhadoop的地址;//如果字符串常量池中不存在javaEEhadoop,则在常量池中加载一份javaEEhadoop,并返回次对象的地址。String s8 = s6.intern();System.out.println(s3 == s8);//true}
示例代码2:
@Testpublic void test3(){String s1 = "a";String s2 = "b";String s3 = "ab";/*如下的s1 + s2 的执行细节:(变量s是我临时定义的)① StringBuilder s = new StringBuilder();② s.append("a")③ s.append("b")④ s.toString() --> 约等于 new String("ab")补充:在jdk5.0之后使用的是StringBuilder,在jdk5.0之前使用的是StringBuffer*/String s4 = s1 + s2;//System.out.println(s3 == s4);//false}
示例代码3:
如果拼接符号左右两边都是字符串常量或常量引用(final修饰的变量也称为--常量),则仍然使用编译期优化,即非StringBuilder的方式。
/*1. 字符串拼接操作不一定使用的是StringBuilder!2.如果拼接符号左右两边都是字符串常量或常量引用,则仍然使用编译期优化,即非StringBuilder的方式。3. 针对于final修饰类、方法、基本数据类型、引用数据类型的量的结构时,能使用上final的时候建议使用上。*/@Testpublic void test4(){final String s1 = "a";final String s2 = "b";String s3 = "ab";String s4 = s1 + s2;System.out.println(s3 == s4);//true}//练习:@Testpublic void test5(){String s1 = "javaEEhadoop";String s2 = "javaEE";String s3 = s2 + "hadoop";System.out.println(s1 == s3);//falsefinal String s4 = "javaEE";//s4:常量String s5 = s4 + "hadoop";System.out.println(s1 == s5);//true}
append效率要比字符串拼接高很多
@Testpublic void test6(){long start = System.currentTimeMillis();// method1(100000);//4014method2(100000);//7long end = System.currentTimeMillis();System.out.println("花费的时间为:" + (end - start));}public void method1(int highLevel){String src = "";for(int i = 0;i < highLevel;i++){src = src + "a";//每次循环都会创建一个StringBuilder、String}
// System.out.println(src);}public void method2(int highLevel){//只需要创建一个StringBuilderStringBuilder src = new StringBuilder();for (int i = 0; i < highLevel; i++) {src.append("a");}
// System.out.println(src);}
体会执行效率:通过StringBuilder的append()的方式添加字符串的效率要远高于使用String的字符串拼接方式!
详情:
① StringBuilder的append()的方式:自始至终中只创建过一个StringBuilder的对象。
② 使用String的字符串拼接方式:创建过多个StringBuilder和String的对象。,内存中由于创建了较多的StringBuilder和String的对象,内存占用更大;如果进行GC,需要花费额外的时间。
改进的空间:
在实际开发中,如果基本确定要前前后后添加的字符串长度不高于某个限定值highLevel的情况下,建议使用构造器实例化,手动指定StringBuilder容器上限大小。
防止超过默认容量大小16而扩容,扩容会将原有的字符串赋值到新的容器当中,原有的容器变成垃圾需要回收。
StringBuilder s = new StringBuilder(highLevel);//new char[highLevel]
public class StringNewTest {public static void main(String[] args) {
// String str = new String("ab");String str = new String("a") + new String("b");}
}
看字节码,就知道是两个。
对象1:new StringBuilder(),变量拼接“+”操作肯定有StringBuilder
对象2: new String("a")
对象3: 常量池中的"a"
对象4: new String("b")
对象5: 常量池中的"b"
深入剖析: StringBuilder的toString():
String源码展示:
如果不是用双引号声明的String对象,可以使用String提供的intern方法: intern方法会从字符串常量池中查询当前字符串是否存在,若不存在就会将当前字符串放入常量池中。
比如: String myInfo = new String("I love u").intern();
也就是说,如果在任意字符串上调用String. intern方法,那么其返回结果所指向的那个类实例,必定和直接以常量形式出现的字符串实例完全相同(字符串常量池当中的对象)。因此,下列表达式的值必定是true: ("a" + "b" + "c").intern()== "abc";
通俗点讲,Interned String就是确保字符串在内存里只有一份拷贝,这样可以节约内存空间,加快字符串操作任务的执行速度。注意,这个值会被存放在字符串内部池(String Intern Pool)。
/*** 如何保证变量s指向的是字符串常量池中的数据呢?* 有两种方式:* 方式一: String s = "shkstart";//字面量定义的方式* 方式二: 调用intern()* String s = new String("shkstart").intern();* String s = new StringBuilder("shkstart").toString().intern();**/
public class StringIntern {public static void main(String[] args) {String s = new String("1");s.intern();//调用此方法之前,字符串常量池中已经存在了"1".即此方法可理解为无效String s2 = "1";//s 指向堆空间"1"的内存地址//s2 指向字符串常量池已存在的"1"的内存地址System.out.println(s == s2);//jdk6:false jdk7/8:falseString s3 = new String("1") + new String("1");//s3变量记录的地址为堆中11,此时字符串常量池当中并不存在11//在字符串常量池中生成"11"。如何理解:jdk6:创建了一个新的对象"11",也就有新的地址。// jdk7:此时常量中并没有创建"11",而是创建一个指向堆空间中new String("11")的地址s3.intern();String s4 = "11";//s4变量记录的地址,使用的是上一行代码执行后在常量池生成的,指向11的地址System.out.println(s3 == s4);//jdk6:false jdk7/8:true}}
面试题拓展:
将String s4 = "11";提到s3.intern();之前。
public class StringIntern1 {public static void main(String[] args) {//StringIntern.java中练习的拓展:String s3 = new String("1") + new String("1");//new String("11")//执行完上一行代码以后,字符串常量池中,是否存在"11"呢?答案:不存在!!String s4 = "11";//在字符串常量池中直接生成对象"11"String s5 = s3.intern();//此时s3.intern全程OB视角,没作为。判断字符串常量池存在11,将s5指向字符串常量池System.out.println(s3 == s4);//falseSystem.out.println(s5 == s4);//true}
}
判断s=="ab",因为是字面量的写法,所以判断的是变量s与字符串常量池当中的"ab"
public class StringExer1 {public static void main(String[] args) {//String x = "ab";String s = new String("a") + new String("b");//new String("ab")//在上一行代码执行完以后,字符串常量池中并没有"ab"String s2 = s.intern();//jdk6中:在串池中创建一个字符串"ab"//jdk8中:串池中没有创建字符串"ab",而是创建一个引用,指向new String("ab"),将此引用返回System.out.println(s2 == "ab");//jdk6:true jdk8:trueSystem.out.println(s == "ab");//jdk6:false jdk8:true}
}
JDK6
JDK7/8
public class StringExer2 {public static void main(String[] args) {String s1 = new String("ab");//执行完以后,会在字符串常量池中会生成"ab"。但是指向堆aa
// String s1 = new String("a") + new String("b");执行完以后,不会在字符串常量池中会生成"ab"s1.intern();//检查字符串常量池当中有ab,有了就全程OB视角,不作为String s2 = "ab";//指向字符串常量池已经存在的abSystem.out.println(s1 == s2); //false}
}
大的网站平台,需要内存中存储大量的字符串。比如社交网站,很多人都存储:北京市、海淀区等信息。这时候如果字符串都调用 intern()方法,就会明显降低内存的大小。
示例代码:
/*** 使用intern()测试执行效率:空间使用上** 结论:对于程序中大量存在存在的字符串,尤其其中存在很多重复字符串时,使用intern()可以节省内存空间。**/
public class StringIntern2 {static final int MAX_COUNT = 1000 * 10000;static final String[] arr = new String[MAX_COUNT];public static void main(String[] args) {Integer[] data = new Integer[]{1,2,3,4,5,6,7,8,9,10};long start = System.currentTimeMillis();for (int i = 0; i < MAX_COUNT; i++) {
// arr[i] = new String(String.valueOf(data[i % data.length]));arr[i] = new String(String.valueOf(data[i % data.length])).intern();}long end = System.currentTimeMillis();System.out.println("花费的时间为:" + (end - start));try {Thread.sleep(1000000);} catch (InterruptedException e) {e.printStackTrace();}System.gc();}
}
示例代码:
-XX:+PrintStringTableStatistics展示字符串常量池信息/*** String的垃圾回收:* -Xms15m -Xmx15m -XX:+PrintStringTableStatistics -XX:+PrintGCDetails**/
public class StringGCTest {public static void main(String[] args) {
// for (int j = 0; j < 100; j++) {
// String.valueOf(j).intern();
// }//发生垃圾回收行为for (int j = 0; j < 100000; j++) {String.valueOf(j).intern();}}
}