Tuesday 21 September 2010

Mutable Integers in java

Because only objects (not primitives) can be stored in Collections data structures, the integer count must be an object, not just an int. The natural choice would be the Integer wrapper type, but it is immutable, which means that once an Integer object is created, its value can never be changed. But here we need to update the value, so here's a class that stores an int that can be changed.

//////////////////////////////////////////////////////////////// value class Int
/** Utility class to keep int as Object but allow changes (unlike Integer).
* Java collections hold only Objects, not primitives, but need to update value.
* The intention is that the public field should be used directly.
* For a simple value class this is appropriate.
*/
class Int {
//=================================================================== fields
public int value; // Just a simple PUBLIC int.

//============================================================== constructor
/** Constructor
@param value Initial value. */
public Int(int value) {
this.value = value;
}
}

No comments:

Post a Comment