|
Re: String manipulations again
|
Posted: Jan 7, 2004 10:19 AM
|
|
From the java api
"If this String object represents an empty character sequence, or the first and last characters of character sequence represented by this String object both have codes greater than '\u0020' (the space character), then a reference to this String object is returned.
Returns: A copy of this string with leading and trailing white space removed, or this string if it has no leading or trailing white space."
and from a post by Matt Gerrans "But of course the only strings in the literal pool would be the strings you literally typed (well, unless you are using a code geneator). This is likely to be a small amount of memory compared to what the computer has, unless you are one hell of a typist.
By the way, one of the advantages of this literal pool is that it saves memory. In this scenario:
String s = new String("Go placidly amid the noise and haste..."); String x = new String("Go placidly amid the noise and haste...");
You have two distinct and separate copies of the same string gobling up defenselsss little memory bits by the hundreds. While in this one:
String s = "Go placidly amid the noise and haste..."; // ... Several gigabytes of painstaking hand-typed code later... String x = "Go placidly amid the noise and haste...";
Both s and x refer to the same String, leaving vast expanses of bored memory circuits with nothing to do."
That explains why you are getting your true and false when you are. Both "String" are refering to the same String in memory so...
if("String".trim()=="String".trim()) its true. //because a reference to the same String is being returned
if("String ".trim()=="String ".trim()) its false //same String in memory but because 2 new Strings are created and references to each are returned it is false
if("String ".trim()=="String") its false //would be false even without trim because they are different Strings in memory if("String".replace(n,g)=="String".replace(n,g)) its false again //again same String in memory but because 2 new Strings are created and references to each are returned it is false
|
|