Java Reference
In-Depth Information
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 is overloaded to provide a no-argument version that performs the increment (
++
) oper-
ator on its value, and also a one-integer version that adds that increment into the value (ana-
logous to the
+=
operator). Because Java doesn't support operator overloading, the calling
class has to call these methods instead of invoking the operations syntactically, as you would
on an
int
. For applications that need this functionality, the advantages outweigh this minor
syntactic restriction. First, let's look at an example of how it might be used. Assume you
need to call a scanner function called, say,
parse()
and get back both a Boolean (indicating
whether a value was found) and an integer value indicating where it was found:
public
public class
StringParse
{
/** This is the function that has a return value of true but
* also "passes back" the offset into the String where a
* value was found. Contrived example!
*/
public
class
StringParse
public static
static
boolean
boolean
parse
(
String in
,
char
char
lookFor
,
MutableInteger whereFound
) {
int
int
i
=
in
.
indexOf
(
lookFor
);
iif
(
i
== -
1
)
return
false
;
// not found
whereFound
.
setValue
(
i
);
return false
// say where found
return
return true
true
;
// say that it was found
}
public
public static
void
main
(
String
[]
args
) {
MutableInteger mi
=
new
static
void
new
MutableInteger
();
String text
=
"Hello, World"
;
char
char
c
=
'W'
;
iif
(
parse
(
text
,
c
,
mi
)) {
System
.
out
.
println
(
"Character "
+
c
+
" found at offset "
+
mi
+
" in "
+
text
);
}
else
else
{
System
.
out
.
println
(
"Not found"
);
}
}
}
Now many OO purists argue—convincingly—that you shouldn't do this, and that you can al-
ways rewrite it so there is only one return value. Either return and have the caller interpret a