问十:不同JDK版本之间intern()方法的区别?(JDK6 与JDK6+)

区别:

这个会不会是因为StringTable移到
这里判断字符串常量池先前是否创建出该字符串对象的方法是:比较字面值(感觉是equal,留个坑,以后补【感觉是对的,直接看JDK API,还是API靠谱准确些,解析放在附1】)

返回的是true
注:在JDK1.6的时候,字符串常量池是存放在Perm Space中的(Perm Space和堆是相隔而开的),在1.6+的时候,移到了堆内存中

示例代码:
JDK1.6

【注意:String s = new String("a")的时候, “a”会被首先创建,放入字符串常量池中,然后new出的对象放在堆中,在调用intern()的时候,会尝试将字符串对象放入字符串常量池中,但是发现字符串常量池中已经有了,就不能放了,在String s2 = "a"的时候,会先在常量池中寻找有没有对应的字符串,如果有,就直接返回它的引用,详情可见面试题笔记中的==与equal    在String s3 = new String("a") + new String("a"),字符串常量池是不会创建“aa”这个字符串的,因为“”中只有单个a,所以在调用intern()的时候,会尝试将“aa”也就是堆中的那个字符串对象放入常量池中,并返回字符串常量池中“aa”的引用,但是由于常量池中放的相当于是一个对象副本,当返回它的引用时,地址是永久区的,因此不会相等】

FALSE FALSE

JDK1.6+

【注意:String s = new String("a")的时候, “a”会被首先创建,放入字符串常量池中,然后new出的对象放在堆中,在调用intern()的时候,会尝试将字符串对象放入字符串常量池中,但是发现字符串常量池中已经有了,就不能放了,在String s2 = "a"的时候,会先在常量池中寻找有没有对应的字符串,如果有,就直接返回它的引用,详情可见面试题笔记中的==与equal    在String s3 = new String("a") + new String("a"),字符串常量池是不会创建“aa”这个字符串的,因为“”中只有单个a,所以在调用intern()的时候,会尝试将“aa”也就是堆中的那个字符串对象的引用放入常量池中,并将该引用返回,由于这两个都是同一个地址引用,于是相等】

FALSE TRUE

再来道有意思的题:


首先,这道题的环境是JDK1.8,JDK1.6答案有所不同
String aString = new String("test");  "test"会被先创建出来,放入字符串常量池。然后new出aString,放在堆内存。
System.out.println(aString.intern() ==  aString);  调用intern时,会先在在字符串常量池中寻找有无当前字符串对象(判断有无似乎用的是equal判断字面值),有的话直接返回字符串常量池中的字符串地址(返回的这个地址所指向的是一个对象还是什么?),因为这时判断字符串常量池中有,那么就返回字符串常量池中对应字符串的地址,两个字符串对象(?) 所在位置不同,地址当然不同,返回false、
String bString = new String("te")+new String("st");  这个其实是创建了四个对象(字符串常量池中的一个te,一个st  堆内存中的两个String对象)
false false

false

true

附1

String java.lang.String.intern()
Returns a canonical representation for the string object.
A pool of strings, initially empty, is maintained privately by the class String.
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.
It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true.
All literal strings and string-valued constant expressions are interned. String literals are defined in section 3.10.5 of the The Java™ Language Specification.
Returns:
a string that has the same contents as this string, but is guaranteed to be from a pool of unique strings.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值