Passing Values
Problem
You need to pass
a number like an
int into a routine, and get back the
routine’s updated version of that value in addition to the
routine’s return value.
This often comes up in working
through strings; the routine may need to return a
boolean, say, or the number of characters
transferred, but also needs to increment an integer array or string
index in the calling class.
It is also useful in constructors, which can’t return a value but may need to indicate that they have “consumed” or processed a certain number of characters from within a string, such as when the string will be further processed in a subsequent call.
Solution
Use a specialized class such as the one presented here.
Discussion
The Integer
class is one of Java’s predefined
Number
subclasses, mentioned in the Introduction
to Chapter 5. It serves as a wrapper for an
int
value, and also has
static methods for parsing and formatting
integers.
It’s fine as it is, but you may want something simpler.
Here is a class I wrote, called
MutableInteger
, that is like an
Integer but specialized by omitting the overhead
of Number and providing only the
set, get, and
incr operations, the latter overloaded to provide
a no-argument version that performs the
increment (++)
operator on its value, and also a one-integer version that adds that
increment into the value (analogous to the +=
operator). Since Java doesn’t support
operator overloading, the calling class has to call these methods instead of invoking the operations ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access