Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

increment of Integer (simple as hell)

Status
Not open for further replies.

1510982

Programmer
Feb 17, 2002
57
SI
Integer x = new Integer(0);

How to increment this x during the further procedure?

Thanks in advance

Rastko
 
Hey Rastko,

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
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top