The return of String.intern() explained

前端 未结 3 1565
粉色の甜心
粉色の甜心 2020-12-20 11:54

Consider:

String s1 = new StringBuilder(\"Cattie\").append(\" & Doggie\").toString();
System.out.println(s1.intern() == s1); // true why?
System.out.prin         


        
3条回答
  •  旧时难觅i
    2020-12-20 12:11

    String literals (those that are hardcoded like "a string") are already interned for you by the compiler. But those strings that are acquired programmatically are not, and will be interned only if you use .intern() method.

    Usually you don't intern strings manually, unless you know you will store in memory a large number of repeating strings, so you can save a lot of memory that way.

    That is explained here: What is Java String interning?

提交回复
热议问题