String类的intern方法的作用:把【new】出来的字符串的引用添加到【StringTable】中,他可以实现运行时动态添加字符串常量池(现在添加的字符串在class文件中的常量池中是不存在),图解如下
案列代码
package com.fh.util.test;
public class bb {
public static void main(String[] args) {
/*String类的intern方法的作用:把【new】出来的字符串的引用添加到【StringTable】中,
他可以实现运行时动态添加字符串常量池(现在添加的字符串在class文件中的常量池中是不存在)*/
/*添加:1.如果StringTable中已经存在对应的字符串的引用,则不做任何操作
2.如果StringTable中不存在对应的字符串的引用,则将调用intern方法的字符串的对象引用添加到StringTable中*/
String c="world";
System.out.println(c.intern()==c);
String d=new String("mike");
System.out.println(d.intern()==d);
String e=new String("jo")+new String("hn");
System.out.println(e.intern()==e);
String b="home";
/*若常量池中存在字符串常量"home",则返回StringTable中的引用地址;若常量池中不存在字符串常量"home",
则将调用intern方法的字符串的对象引用添加到StringTable中并返回引用地址*/
String g=new String("ho")+new String("me");
System.out.println(g.intern()==g);
String f=new String("ja")+new String("va");
System.out.println(f.intern()==f);
String h=new String("vo")+new String("id");
System.out.println(h.intern()==h);
}
}
版权声明:本文为qq_36513313原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。