0
点赞
收藏
分享

微信扫一扫

Java中的String的intren方法详解

yellowone 2023-04-22 阅读 95

intern 方法会从字符串常量池中查询当前字符串是否存在,若不存在就会将当前字符串放入常量池

String a=new String("hello").intern();
String b="hello";
System.out.println(a==b);//

String a=new String("hello");
a.intern();
String b="hello";
System.out.println(a==b);//

关键点是 jdk7 中常量池不在 Perm 区域了,这块做了调整。常量池中不需要再存储一份对象了,可以直接存储堆中的引用。这份引用指向s3 引用的对象。 也就是说引用地址是相同的。

String s3=new String("a")+new String("b");//常量池中是没有“ab”的
s3.intern();
String s4="ab";
System.out.println(s3==s4);//true

Java中的String的intren方法详解_字符串

举报

相关推荐

0 条评论