Java Reference
In-Depth Information
public class Example<T> {
private T a, b, c[], d;
public Example(T in) {
a = in;
b = in;
c = (T[]) new Object[10];
d = in;
}
}
When an
Object
method, such as
toString()
, is overridden, a programmer could ac-
cidentally provide an implementation for type
T
that fails to consider that
c
is an array of
T
rather than a reference to an object of type
T
.
public String toString() {
return a.toString() + b.toString() +
c.toString() + d.toString();
}
However, the programmer's intent could have been to invoke
toString()
on each in-
dividual element of the array
c
.
// Correct functional implementation
public String toString() {
String s = a.toString() + b.toString();
for (int i = 0; i < c.length; i++){
s += c[i].toString();
}
s += d.toString();
return s;
}