I take it that you have a specific reason for making the Integer value an Integer object and not just declaring it as a primitive, ie:
int x = 0;
Declaring it as a primitive makes it dead simple to incriment. Using an Integer wrapper class makes it not so straight forward. Once an Integer instance is created, you cannot change its value.
The IntegerString, Float, Double, Byte, Long, Short, Boolean, and Character classes are all examples of an immutable class. By definition, you may not alter the value of an immutable object after its construction.
In Java, a class such as Integer acts as a simple wrapper around its primitive counterpart -- in this case, int. The wrappers found in java.lang allow us to treat the primitives as if they were objects. So, for example, you could not put an int into a Vector without wrapping it with an Integer object first. Immutable classes offer a number of advantages. First, a method cannot alter an immutable object in an unexpected way. Because a method cannot leave the object in some unexpected state, you avoid a number of bugs. Second, an immutable object is intrinsically thread safe. Since a thread cannot alter the object, you do not need to protect the object from concurrent thread access.
Of course, if you need to alter your Integer instances you are out of luck. You can write your own mutable integer wrapper class for use by your own objects. However, you cannot do anything about third-party objects that return java.lang.Integer instances
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.