【java基础】String的深坑

1. intern()

《深入理解Java虚拟机》中的描述:

  1. String.intern()是一个Native方法,它的作用是:如果字符串常量池中已经包含一个等于此String对象的字符串,则返回代表池中这个字符串的String对象;否则,将此Sreing对象包含的字符串添加到常量池中,并且返回此String对象的引用。
  2. Jdk1.7的intern()实现不会再复制实例,只是在常量池中记录首次出现的实例引用

String源码注释:

  1. 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.

【例1】

代码1:
String s1=new String("11")+new String("11");
s1.intern();
String s2="1111";
System.out.println(s1==s2); //true
代码2:
String s1=new String("11")+new String("11");
String s2="1111";
System.out.println(s1==s2);  //false

解释:String s1=new String(“11”)+new String(“11”);在堆中存”1111“,在常量池中存”11“,当执行intern()的时候,因为常量池中没有”1111“,所以就把堆中的”1111“的实例引用放到常量池中。当执行String s2="1111"的时候,首先去常量池看看有没有“1111”,这时发现有,就得到了s1的引用,所以s1==s2是true;而不执行s1.intern()时,由于s1是堆中存的引用,s2是常量池的,所以s1!=s2。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值