Quote:
If a static final field has a mutable reference type, it can still be a constant field if the referenced object is immutable.
I'm not sure what this mean; can someone give an example of that?
An example that Josh is talking about would be List
, which is a mutable type ( add()
, remove()
, etc), but you can assign an immutable instance to it:
public static final List<String> NAMES = Collections.unmodifiableList( Arrays.asList("foo", "bar")); // immutable
By the way, a great example of something that looks like a constant, but isn't, is a Date
constant:
public static final Date EPOCH = new Date(0);
but then some code can do this:
EPOCH.setTime(123456789); // oops!
Date
is mutable ! Everyone will see such a change.
In constrast with this is something like String
, which is immutable:
public static final String NAME = "Agent Smith"; // immutable
You can have a mutable type with an immutable subtype:
class Mutable {} // Not immutable, because it can be extended.
final class Immutable extends Mutable {}
// Reference type is mutable, but referenced object is immutable.
static final Mutable CONSTANT = new Immutable();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.