-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
Rob Jones wrote:
Hi all,
Anyone know the details about String immutability ?
I understand the need to have imutable strings at compile time.
However if at runtime I have say 8000 strings and then I make
a new string from an existing string using substring
does that mean that my exisint 8000 strings will be searched
incase I am making a duplicate ?
That seems quite an overhead ?
Equally once I have created this new String once it becomes
eligible for garbage collection will the immutable String
be removed from the immutable string collection ?
IE will I just lose a reference to an immutable String object
or will that immutable String object be resuable for new
String objects that are created to have the same value ?
Does that mean creating/deleting lots of Strings can build
up an unfreeable area of memory ?
Thanks
Rob
Hello,
This is not exactly what immutability means. Your example implies that
it is impossible to have two completely separate objects of type
java.lang.String, both of which happen to contain the same text. In
fact, this is very possible. What immutability really means is that,
given a certain java.lang.String object, it is impossible to change
the text inside it, as evidenced by the fact that methods like
substring() actually return a *new* java.lang.String containing the
substring, they *don't* modify the existing one.
What you were actually describing is the so-called "canonical
representation" mechanism, implemented by the intern() method of the
String class. This is completely unrelated to immutability with the
exception that the canonical representation mechanism could not exist
without the immutability property. Obviously, you never actually need
to call intern() unless you have a good reason.
- --
Chris
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.2 (GNU/Linux)
iD4DBQFAa2z2nwjA8LryK2IRAk/dAJdVa95zxPvSMUtVfHjon608RznlAJ45jvNh
rA8fkwLfXWeIJMyt/wac3Q==
=/N6h
-----END PGP SIGNATURE-----