Java String 的 intern() 方法问题
ringa_lee
ringa_lee 2017-04-17 16:10:00
0
3
781

请问两种方式是否等价?

    HashMap map = new HashMap<>();
    map.put("abc", 1); //1
    map.put("abc".intern(), 1);//2
ringa_lee
ringa_lee

ringa_lee

reply all(3)
小葫芦

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

洪涛

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.

PHPzhong
  1. 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

  2. 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

      • 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 object is returned.
🎜 🎜🎜 🎜🎜 🎜 🎜 🎜🎜 🎜 🎜
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template