Avoid duplicate Strings in Java

前端 未结 5 1090
独厮守ぢ
独厮守ぢ 2021-01-03 09:37

I want to ask a question about avoiding String duplicates in Java.

The context is: an XML with tags and attributes like this one:



        
5条回答
  •  执笔经年
    2021-01-03 09:57

    As everyone know, String objects can be created in two ways, by using the literals and through new operator.

    If you use a literal like String test = "Sample"; then this will be cached in String object pool. So interning is not required here as by default the string object will be cached.

    But if you create a string object like String test = new String("Sample"); then this string object will not be added to the string pool. So here we need to use String test = new String("Sample").intern(); to forcefully push the string object to the string cache.

    So it is always advisable to use string literals than new operator.

    So in your case private static final String id = "PROD"; is the right solution.

提交回复
热议问题