String的intern()函数|JVM运行时数据区

这里会涉及到几个概念,先提出来:

1、JVM规范认为Java虚拟机一般包含五个部分:堆、虚拟机栈、本地方法栈、程序计数器、方法区。运行时常量池是方法区的一部分。

2、HotSpot中对方法区的实现称为永久代,分清楚规范和实现之间的概念差异。

3、不同虚拟机版本实现有变化,Java7中存在永久代,但是永久代中运行时常量池已经迁出到堆中,Java8中已经没有永久代,新增Metaspace元空间,运行时常量池在堆中。

下面我们再来看看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.

主要意思就是说从常量池中返回和当前对象equals()相等的对象,如果常量池中不存在这样的对象,先在常量池中实例化这个对象,然后返回这个对象在常量池中的引用。所以Java版本会影响这个函数的表现,但是他的功能是没有变化的。来看个例子:

猜你喜欢

转载自blog.csdn.net/tales522/article/details/81260704