In this case, JVM searches String constant pool for value "Ram", and if it does not find it there then it allocates a new memory space and store value "Ram" and return its reference to name1. Similarly, for name2 it checks String constant pool for value "Ram" but this time it fin...
如果一个String是可变的,当改变了A引用指向的String时,可能就会导致其他的B引用得到错误的值,所以Sting就被设计为不可变的。String底层主要是使用intern缓存池将字符串缓存起来,同时允许把一个String字符串的地址赋值给多个String变量来引用,这样就可以保证多个变量安全地共享同一个对象。如果Java中的String对象可变的...
private static final WeakHashMap<String, WeakReference<String>> MANUAL_CACH=new WeakHashMap<>(100003); private static String manuIntern( final String str ) { final WeakReference <String> cached = MANUAL_CACH.get( str ); if ( cached != null){ final String value = cached.get(); if (valu...
import java.util.Random; import java.util.concurrent.TimeUnit; public class StringInternTest { static final int MAX = 1000 * 10000; static final String[] arr = new String[MAX]; public static void main(String[] args) throws InterruptedException { Integer[] DB_DATA = new Integer[10]; Rando...
intern()是java.lang.String对象中一个有趣的函数。intern()函数从应用程序中消除重复的字符串对象,并有可能减少应用程序的整体内存消耗。在这篇文章中,让我们更多地了解这个intern()函数。 1. String intern() 函数是如何工作的? 在Java堆内存中,维护了一个字符串对象池。当您在 String 对象上调用intern()函数...
用双引号创建的 String ,自动使用常量池,比如 String a = "test"; 使用 String 的 intern 方法,使用常量池,比如 String s = new String(new char[]{'a','b','c'}); String intern = s.intern(); // 类似于上面的pool.putIfAbsent(s, s) 和 pool.get(s) 关于 intern 方法,JDK 文档这样写:当...
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...
public class StringExistInPoolBeforeIntern { public static void main(String[] args){ String stringObject = new String("tomcat"); //NOTE 在intern之前,string table已经有了tomcat,因而intern返回tomcat,不会指向stringObject stringObject.intern(); String stringLiteral = "tomcat"; System.out.println(...
String#intern方法中可以看出,这个方法是一个native的方法,但注释写的非常明了:“如果常量池中存在当前字符串, 就会直接返回当前字符串.。如果常量池中没有此字符串, 会将此字符串放入常量池中后, 再返回”。 2.jdk6、jdk7下intern的区别# 相信很多 JAVA 程序员都做过类似String s = new String("abc")这个...
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?