您的位置:首页 > 编程语言 > Java开发

阅读String源码总结【jdk1.6】

2016-02-29 14:58 525 查看
1、打开String源码发现String其实就是字符数组char[];

2、String定义了三个变量value、offset、count(hash暂且不说),value是String的值,offset是偏移量,count是字符串长度;

3、之所以说String是不可变的,是因为value、offset、count三个变量都是用private final修饰的,在外界访问不到,所以只能新建一个String。

(但是可以通过反射的方式修改String的值)

String s = "hello world";
System.out.println("s = "+ s);
Field valueOfString = String.class.getDeclaredField("value");
valueOfString.setAccessible(true);
char[] value = (char[]) valueOfString.get(s);
value[5] = '_';
System.out.println("s = "+ s);
输出结果:
s = hello world

s = hello_world

4、对于offset的用法一直不理解,以为值一直为0,结果发现substring和trim方法中修改了offset的值:

当我们使用substring或者trim方法返回当前字符串的子字符串时,栈中并没有生成新的字符集合,而是在堆中新建一个引用并指向了同一个字符集合并且修改offset和count的值。

String s = new String(" hello world   ");
String s1 = s.substring(7,12);
String s2 = s.trim();
Class<String> c =String.class;
Field f = c.getDeclaredField("offset");
Field f1 = c.getDeclaredField("count");
f1.setAccessible(true);
f.setAccessible(true);
System.out.println("original  offset :"+f.get(s));
System.out.println("substring offset :"+f.get(s1));
System.out.println("trim	  offset :"+f.get(s2));
System.out.println("original  count  :"+f1.get(s));
System.out.println("substring count  :"+f1.get(s1));
System.out.println("trim 	  count  :"+f1.get(s2));
输出结果:

original  offset :0

substring offset :7

trim  offset :1

original  count  :15

substring count  :5

trim  count  :11

也就是说字符s1、s2字符串的value字符数组和s的value是同一个,只是改了一下偏移量offset和长度count而已。

String s = new String("hello world");
String s1 = s.substring(6);
Class c =String.class;
Field f1 = c.getDeclaredField("value");
f1.setAccessible(true);
char[] value = (char[]) f1.get(s);
char[] value1 = (char[]) f1.get(s1);
System.out.println(s);
System.out.println(s1);
System.out.println(value == value1);
输出结果:

hello world   

world   

true

再举个例子,修改其中一个的value值,则全部改变。

String s = new String("hello world");
String s1 = s.substring(6);
Class<String> c =String.class;
Field f1 = c.getDeclaredField("value");
f1.setAccessible(true);
char[] value = (char[]) f1.get(s);
System.out.println("before s="+s);
System.out.println("before s1="+s1);
value[6] = 'W';
System.out.println("after s="+s);
System.out.println("after s1="+s1);
输出结果:

before s=hello world

before s1=world

after s=hello World

after s1=World
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: