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

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值