5.4 Specify Object Arguments Over Primitives
As discussed in Chapter 4, Tiger adds a variety of new features through
unboxing. This allows you, in the case of varargs, to use object wrapper types in your method arguments.
5.4.1 How do I do that?
Remember that every class in Java ultimately is a descendant of java.lang.Object. This means that any object can be converted to an Object;
further, because primitives like int and short are now automatically
converted to their object wrapper types (Integer and Short in this case),
any Java type can be converted to an Object.Thus, if you want to accept the widest variety of argument types in your
vararg methods, use an object type as the argument type. Better yet, go
with Object for the absolute most in versatility. For example, take a
method that did some printing:
The basic idea here is to print anything and everything. However, the
private String print(Object... values) {
StringBuilder sb = new StringBuilder( );
for (Object o : values) {
sb.append(o)
.append(" ");
}
return sb.toString( );
}
more obvious way to declare this method is like this:
The problem here is that now this method won't take Strings, ints, floats, arrays, and a variety of other types, all of which you might want to legitimately print.By using a more general type, Object, you obtain the ability to print anything and everything.
private String print(String... values) {
StringBuilder sb = new StringBuilder( );
for (Object o : values) {
sb.append(o)
.append(" ");
}
return sb.toString( );
}