Java Strings: “String s = new String(”silly“);”

前端 未结 23 2458

I\'m a C++ guy learning Java. I\'m reading Effective Java and something confused me. It says never to write code like this:

String s = new String(\"silly\");         


        
23条回答
  •  孤街浪徒
    2020-11-22 14:33

    Java strings are interesting. It looks like the responses have covered some of the interesting points. Here are my two cents.

    strings are immutable (you can never change them)

    String x = "x";
    x = "Y"; 
    
    • The first line will create a variable x which will contain the string value "x". The JVM will look in its pool of string values and see if "x" exists, if it does, it will point the variable x to it, if it does not exist, it will create it and then do the assignment
    • The second line will remove the reference to "x" and see if "Y" exists in the pool of string values. If it does exist, it will assign it, if it does not, it will create it first then assignment. As the string values are used or not, the memory space in the pool of string values will be reclaimed.

    string comparisons are contingent on what you are comparing

    String a1 = new String("A");
    
    String a2 = new String("A");
    
    • a1 does not equal a2
    • a1 and a2 are object references
    • When string is explicitly declared, new instances are created and their references will not be the same.

    I think you're on the wrong path with trying to use the caseinsensitive class. Leave the strings alone. What you really care about is how you display or compare the values. Use another class to format the string or to make comparisons.

    i.e.

    TextUtility.compare(string 1, string 2) 
    TextUtility.compareIgnoreCase(string 1, string 2)
    TextUtility.camelHump(string 1)
    

    Since you are making up the class, you can make the compares do what you want - compare the text values.

提交回复
热议问题