Home  >  Article  >  Java  >  Why is 'CaseInsensitiveString cis = new CaseInsensitiveString('Polish')' acceptable while 'String s = new String('silly')' is discouraged for memory optimizatio

Why is 'CaseInsensitiveString cis = new CaseInsensitiveString('Polish')' acceptable while 'String s = new String('silly')' is discouraged for memory optimizatio

DDD
DDDOriginal
2024-11-14 14:09:02333browse

Why is

Java String Memory Optimization: Understanding "String s = new String("silly")"

Concern has been raised regarding the recommendation to avoid writing Java code like "String s = new String("silly")". While this advice is valid for optimizing memory usage in the case of String objects, it may not be applicable to other classes.

Why is "CaseInsensitiveString cis = new CaseInsensitiveString("Polish")" acceptable?

The object "cis" is an instance of the CaseInsensitiveString class. Unlike String, CaseInsensitiveString is a user-defined class that requires a constructor to create an object. Therefore, the syntax "CaseInsensitiveString cis = new CaseInsensitiveString("Polish")" is necessary to initialize the object with the specified string value.

How to make CaseInsensitiveString behave like String for literal initialization?

To enable literal initialization for CaseInsensitiveString as it is for String, one could implement the following:

  • Create a custom factory method: Define a static method in the CaseInsensitiveString class that takes a literal as an argument and returns an instance of the class initialized with that value. This method would mimic the implicit constructor call that occurs for String literals.
  • Implement the valueOf() method: Override the valueOf() method inherited from Object, which is used internally by Java to create new String instances from literals. By providing a custom implementation, one could create new CaseInsensitiveString objects directly from literals.

Why is it okay to directly pass a literal to String?

String is a special class in Java. It has a predefined pool of interned strings, where duplicate string literals are stored as references to the same object. This eliminates the need for multiple String objects for the same string value, reducing memory consumption.

The above is the detailed content of Why is 'CaseInsensitiveString cis = new CaseInsensitiveString('Polish')' acceptable while 'String s = new String('silly')' is discouraged for memory optimizatio. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn