请问两种方式是否等价?
HashMap map = new HashMap<>();
map.put("abc", 1); //1
map.put("abc".intern(), 1);//2
高洛峰2017-04-17 16:12:00
The constant pool in the .class file will be loaded by the JVM during runtime and can be expanded. The intern() method of String is a method to expand the constant pool; when a String instance str calls the intern() method, Java checks whether there is a string constant with the same Unicode in the constant pool, and if so, returns its reference. If If not, add a Unicode string equal to str in the constant pool and return its reference.
So these two should be equivalent
PHP中文网2017-04-17 16:12:00
are equivalent. First of all, the intern() of your second statement is completely unnecessary. "abc" itself will be compiled into the constant pool, so your intern() will not do anything.
PHPz2017-04-17 16:12:00
The put method of HashMap will calculate the hash value of the key, so it will be the same whether the String is returned from the constant pool or new
As you can see from the comments of the intern() method, it will look for the string from the String constant pool. If it finds it, it will return the string in the constant pool. If it does not find it, it will add the string to the constant pool and then return.
When the intern method is invoked, if the pool already contains a
string equal to this String
object as determined byString
object as determined by
the {@link #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
String
object is added to theString
object is returned.