Philipp wrote:
Patricia Shanahan wrote:
I don't understand clone's attraction for a class such as String, a
final class with immutable instances.
Perhaps you could explain why you would prefer a clone to a reference to
the original String?
Sorry I did'nt know that String was immutable. How do you tell from the
JavaDoc if a class is immutable?
By reading where it says "Strings are constant; their values
cannot be changed after they are created. [...] Because String
objects are immutable [...]"
However:
"Immutable" is a slightly fuzzy concept. We say that a class
is "immutable" if the value of an instance cannot be changed after
the instance is constructed. Well, what exactly do we mean by the
"value" of an object? Here's a class:
public class Immutable {
private final Object value;
public Immutable(Object value) {
this.value = value;
}
public String toString() {
return String.valueOf(value);
}
}
Is an Immutable instance "immutable" or "mutable?" It encapsulates
an Object reference, and that reference can't change, so in that
sense it's "immutable." But if I write
StringBuffer sb = new StringBuffer("Hello");
Immutable im = new Immutable(sb);
System.out.println(im);
sb.append(", world!");
System.out.println(im);
have I changed the "value" of the Immutable instance? Maybe yes,
maybe no. The two lines of printed output are clearly different,
so "something about" the Immutable instance has changed, even though
not a single bit of the memory devoted to the instance has flipped.
The notion of "immutability" depends, really, on the "purpose" of
the class -- and "purpose" is a tricky notion to pin down.
Even the classes that most people will call "immutable" usually
aren't, if sufficiently drastic steps are taken. The canonical
example of an "immutable" class is surely String, yet code has been
posted here that uses reflection to get at and modify the char[]
underlying the String. If the same String object prints as "Hello"
once and as "world" later, has its value changed? Most people would
say that it has -- and so we modify "immutable" to be "immutable
except under special circumstances," and "special" is yet another
hard-to-define word.
--
Eric Sosman
esosman@acm-dot-org.invalid
its semantic value after instantiation.
class is mutable. Often times it takes special care to ensure that a
This class is immutable.