JDK每次升级都会做很多优化,我们使用最多的String常量类也在不断被优化。这次和大家分享的是JDK1.8中对String的优化之一,intern()方法的使用。
对应的方法及注释如下:
/**
- Returns a canonical representation for the string object.
- A pool of strings, initially empty, is maintained privately by the
- class {@code String}.
- When the intern method is invoked, if the pool already contains a
- string equal to this {@code String} object as determined by
- the {@link #equals(Object)} method, then the string from the pool is
- returned. Otherwise, this {@code String} object is added to the
- pool and a reference to this {@code String} object is returned.
- It follows that for any two strings {@code s} and {@code t},
- {@code s.intern() == t.intern()} is {@code true}
- if and only if {@code s.equals(t)} is {@code 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.
- @return a string that has the same contents as this string, but is
- guaranteed to be from a pool of unique strings.
*/
public native String intern();
一句话概括,就是通过常量池复用来节省内存空间、减少开销以提升性能。
Tips:
这里简单介绍一下常量池,方便下文理解。先看看JVM的内存结构:
我们的常量池就在方法区中,在实际应用中会跟堆区配合使用。平时大家都统称它为常量池,严格划分的话常量池又分为:静态常量池、运行时常量池和字符串常量池。三者的区别,有时间会写一篇单独的博客。
回到今天的主题,intern()方法。如果我们对着英文注释一句一句翻译,来理解它的话会很有限很苦涩,结合代码示例理解会更好一些(个人经验)。
示例一:
public static void main(String[] args) {
String str1 = "abc";
String str2 = new String("abc");
String str3 = str2.intern();
System.out.println("str1==str2: " + (str1 == str2)); // false
System.out.println("str2==str3: " + (str2 == str3)); // false
System.out.println("str1==str3: " + (str1 == str3)); // true
}
1
2
3
4
5
6
7
8
9
运行结果:
str1str2: false
str2str3: false
str1==str3: true
1
2
3
分析,str2.intern()被调用时,str1 = “abc” 已经将“abc”放入了常量池,根据方法注释,str3返回的是拿到的是常量池中的str1,str2还是对象引用。所以有了上面的结果。
示例二:
public static void main(String[] args) {
String str1 = new String("abc");
String str2 = new String("abc");
System.out.println(str1 == str2); //false
System.out.println(str1.intern() == str2.intern()); //true
}
1
2
3
4
5
6
7
运行结果:
false
true
1
2
分析,str1==str2为false就不用说了;str1.intern() == str2.intern()为true,在英文注释里有说:
s.intern() == t.intern() is true if and only if s.equals(t) is true.
也是就是两个String对象,当且仅当它俩equals()比较值为true,那它俩intern()的“==”操作也为true。
————————————————
版权声明:本文为CSDN博主「pbxs」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/WLQ0621/article/details/107465898