Pregunta

I know Integers are immutable in Java. But why it is designed this way?

I went through other answers before asking this question:

Is Integer Immutable

i++ still working for immutable Integer in Java?

Why are Java wrapper classes immutable?

But I couldn't find the use case which mandates the Integer to be immutable. Are there any technical reasons like there are for String?

  1. String is used as parameter in network connection, database URLs etc. It could easily be compromised if it was mutable.
  2. To support StringPool facility.
  3. To support class loading mechanism in which Strings are used as arguments. String being mutable results in a wrong class being loaded.

I understand there are wrappers like AtomicInteger for mutable.

UPDATE:

From the conversation, there is no universal reason that could mandate the Integers being immutable. However by doing immutable it provides some bonus as mentioned in the answers.

Such as this quote from Andrey

possibility to cache.

Others are reducing global state

easier multithreading

¿Fue útil?

Solución

You won't find a mandatory reason why java.lang wrappers must be immutable. Simply because it's a design decision. They could have decided otherwise. The language designers had to choose between mutable and immutable. And they chose immutable. That's it.

There are some compelling (IMO) reasons though to make them immutable:

It's consistent with String. The same reasoning you provided for String to be immutable applies to Integer etc. as well (e.g. think of a port number in a property map). This generally applies to any mutable type.

Immutable types rule out a plethora of hard to find mistakes one can make where one involuntarily changed an objects member value by modifying the value obtained through a getter. It saves a lot of defensive copying when the type is immutable. The most infamous example is java.util.Date, which is generally a pain to use because it's mutable (API issues aside).

Also immutable types allow for the use of shared instances, like e.g. Integer does for commonly used values (see Integer.valueOf(int)).

Otros consejos

Can the identity of the value 1 ever change? Can it become 2? No. That's why Integer and other numeric types are immutable. They're meant to model that identity.

An integer literal (2, 3) is also immutable e.g. int var=3; It's the int variable (var on the left had side) that is mutable. The intention of Integer is "object as a value" (right hand side) rather than "object as a variable" (left hand side). Since Java uses references, variability (mutability) can be either in reference or in the object contents. The object reference (variable r in Integer r=2;) can be the variable aspect of this situation. As a result, variability is provided via a "variable reference" rather than "constant reference (i.e. no reference) to a variable primitive-typ content". It would be using a constant reference (constant r) and a variable content of the referred object.

They could have designed the class name Integer as a variable (non-immutable) but then eventually another class name would have been necessary for immutable (right-hand side value). So MutableInteger and ImmutableInteger both can be used in programs in one form or another. However, people happen to use the latter more often. So, early on Java developers decided to use the shorter name Integer for the latter (ImmutableInteger). There are various reasons why the latter turns out to be more useful and less error-prone that are explained well in other answers to this post. Both are possible and they both exist, just there is more demand for the latter.

In order for an object reference to encapsulate a value which is under the control of the thing that holds it, one of three conditions must apply:

  1. The class of the object must be immutable.

  2. The reference must identify an instance that will never be exposed to anything that might mutate it.

  3. The reference must never be shared with any object which isn't under the control of its holder, whether or not such a thing would mutate it.

Code which holds references of type Integer generally does so for the purpose of encapsulating integer values. Making Integer immutable makes it possible for classes to freely share references that are used to encapsulate value. Although there are times when a MutableInteger class would itself be useful [such a thing could probably be a little cleaner than a single-element int[] and more efficient than an AtomicInteger], one wouldn't pass a MutableInteger class to a method as a means of passing the number therein; one would instead pass it for the purpose of giving that method a place to store a number.

I think immutability is a design choice that relates with garbage collection mechanism. At least, immutability helped the garbage collection to works more efficiently due to removal of several overhead mechanism that needs to be taken to guarantee the integrity of an object.

Earlier programming languages were invented in the era where the limitation of hardware constraints are pretty obvious (e.g. RAM and speed of processor and no runtime / bare to metal approach). In such environment, you need to be very careful about object instantiation, and, once it is instantiated, you should update it instead of throwing away for new values. In this respect, JAVA was one pioneer for popularizing the new approach with runtime and garbage collection - which - goes hand in hand with immutability.

Note that, more recent interpreters that use bytecodes such as Python (as opposed to, say, Perl) also use the immutability of integers and simple types.

From this source:

Programmers are often reluctant to employ immutable objects, because they worry about the cost of creating a new object as opposed to updating an object in place. The impact of object creation is often overestimated, and can be offset by some of the efficiencies associated with immutable objects. These include decreased overhead due to garbage collection, and the elimination of code needed to protect mutable objects from corruption.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top