一、前言
String 类型是 java 里面一个很特殊的存在,里面涉及到了很多使用细节以及很多基础知识,并且常常在面试中会被当做基础部分进行提问,而 String 的 intern 方法更是很多人听都没有听过,更不要说使用了,所以本篇文章来解析下 intern 方法,掀起 intern 的盖头来 !
二、正文
1.字符串常量池
字符串常量池其实就是一个固定长度的 HashTable,是 Java 提供的系统级别的一个 Cache,为了节省内存以及提升性能。
下面来看一下一个例子,相信在笔试或者面试的时候经常会遇到这么一个问题,String a = new String(“1”); 这行代码到底创建了多少个对象?
-
第一种情况,如果当前字符串常量池不存在 “1”,那么就会创建两个对象,一个在常量池中,一个在堆中。
-
第二种情况,如果当前字符串常量池已经存在了 “1”,那么只会创建一个对象,这个对象在堆中。
通过上面的例子可以看出,其实每次使用魔法值的时候,都会往常量池中存储一份,这样以后使用的时候可以直接从常量池中使用,并且常量池的一个加载都是在编译器就已经确认好的,性能提升不少。
2.intern() 含义
官方注释:
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.
上面的意思大概就是,使用intern方法的时候,会去常量池中判断是否存在这个字符串对象,如果不存在,就往常量池中存储一份,然后返回池中对应的对象。
如果存在了,那么直接返回池中存在的字符串对象。
3. intern() 实战
场景一:
public class Main {
public static void main(String[] args) {
String a = new String("1");
a.intern();
String b