I encountered the following code in Joshua Bloch's Effective Java book but I can't understand why the pickTwo
method returns Object[]
? The method toArray
returns Integer[]
. So why does pickTwo
return Object[]
? I think it should return Integer[]
.
Joshua Bloch's book says that:
The type of this array is determined by the compile-time types of the arguments passed in to the method, and the compiler may not have enough information to make an accurate determination. Because this method returns its varargs parameter array,
pickTwo
will always return an array of typeObject[]
.
public class JavaApplication52 {
public static void main(String[] args) {
System.out.println(toArray(1,2,3));
System.out.println(pickTwo(1,2,3));
}
static <T> T[] pickTwo(T a, T b, T c) {
switch (ThreadLocalRandom.current().nextInt(3)) {
case 0:
return toArray(a, b);
case 1:
return toArray(a, c);
case 2:
return toArray(b, c);
}
throw new AssertionError(); // Can't get here
}
static <T> T[] toArray(T... args) {
return args;
}
}
OUTPUT:
[Ljava.lang.Integer;@6d06d69c
[Ljava.lang.Object;@70dea4e