search

Home  >  Q&A  >  body text

Java String 的 intern() 方法问题

请问两种方式是否等价?

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

reply all(3)I'll reply

  • 高洛峰

    高洛峰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

    reply
    0
  • PHP中文网

    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.

    reply
    0
  • PHPz

    PHPz2017-04-17 16:12:00

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

    reply
    0
  • Cancelreply