我在 Joshua Bloch 的《Effective Java》一书中遇到了以下代码,但我不明白为什么 pickTwo
方法返回 Object[]
?方法toArray
返回Integer[]
。那么为什么 pickTwo
返回Object[]
?我认为它应该返回 Integer[]
.
约书亚·布洛赫 (Joshua Bloch) 的书说:
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;
}
}
输出:
[Ljava.lang.Integer;@6d06d69c
[Ljava.lang.Object;@70dea4e
最佳答案
您已经在问题中解释了自己。由于 pickTwo()
采用泛型,因此当它调用 toArray()
时,编译器不知道什么类会传递给 pickTwo()
然后在调用 toArray() 时使用。由于这只能在运行时知道,因此您只需得到 Object
([Ljava.lang.Object;@70dea4e
))
当您在编译时使用 int
显式调用 toArray()
时,编译器可以确定返回类型。
关于java - 为什么从另一个泛型方法调用的泛型可变参数方法会返回 Object[]?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49723078/