I already know the definition of immutable classes but I need a few examples.
Some famous immutable classes in the Standard API:
Most enum classes are immutable, but this in fact depends on the concrete case. (Don't implement mutable enums, this will screw you up somewhen.) I think that at least all enum classes in the standard API are in fact immutable.
java.math.BigInteger and java.math.BigDecimal (at least objects of those classes themselves, subclasses could introduce mutability, though this is not a good idea)
java.io.File. Note that this represents an object external to the VM (a file on the local system), which may or may not exist, and has some methods modifying and querying the state of this external object. But the File object itself stays immutable. (All other classes in java.io are mutable.)
java.awt.Font - representing a font for drawing text on the screen (there may be some mutable subclasses, but this would certainly not be useful)
java.awt.Cursor - representing the bitmap for the mouse cursor (here too, some subclasses may be mutable or depending on outer factors)
java.util.Locale - representing a specific geographical, political, or cultural region.
while most collections are mutable, there are some wrapper methods in the java.util.Collections class, which return an unmodifiable view on a collection. If you pass them a collection not known anywhere, these are in fact immutable collections. Additionally, Collections.singletonMap()
, .singletonList
, .singleton
return immutable one-element collections, and there are also immutable empty ones.
java.net.URL and java.net.URI - representing a resource (on the internet or somewhere else)
java.time
except DateTimeException
are immutable. Most of the classes of the subpackages of java.time
are immutable too.One could say the primitive types are immutable, too - you can't change the value of 42, can you?
is Class AccessControlContext a immutable class
AccessControlContext does not have any mutating methods. And its state consists of a list of ProtectionDomains (which is an immutable class) and a DomainCombiner. DomainCombiner is an interface, so in principle the implementation could do something different on each call.
In fact, also the behaviour of the ProtectionDomain could depend on the current policy in force - it is disputable whether to call such an object immutable.
and AccessController?
There are no objects of type AccessController, since this is a final class with no accessible constructor. All methods are static. One could say AccessController is neither mutable nor immutable, or both.
The same is valid for all other classes which can't have objects (instances), most famously:
in
, out
, err
)