为什么重载方法选择的是 Object 而不是原始数组的 Object[]?
Why is selected Object instead of Object[] with primitive array for overloaded methods?
当我运行这段代码时:
class Test {
public static void main(String[] args) throws Exception {
someMethod(new int[] {1, 2, 3});
}
static void someMethod(Object obj) {
System.out.println("Single object given: " + obj);
}
static void someMethod(Object[] objs) {
System.out.println("Multiple objects given: " + Arrays.toString(objs));
}
}
我得到其中 someMethod(Object[] objs)
被选择为 int[]
的输出:
Single object given: [I@140e19d
我在尝试记录一些消息时遇到了这样的行为:
logger.log(Level.INFO, "param1: {0}, param2: {1}", new int[] {1, 2});
输出:
...
INFO: param1: [I@103dbd3, param2: {1}
那么为什么选择Object而不是Object[]作为原始数组的方法参数呢?
因为 int[]
不是 Object[]
- 就这么简单。 Object[]
的元素必须是引用 - int[]
的元素是 而不是 引用。
JLS section 4.10.3 讨论数组的子类型关系 - 特别是:
If S
and T
are both reference types, then S[] >1 T[]
iff S >1 T
.
当我运行这段代码时:
class Test {
public static void main(String[] args) throws Exception {
someMethod(new int[] {1, 2, 3});
}
static void someMethod(Object obj) {
System.out.println("Single object given: " + obj);
}
static void someMethod(Object[] objs) {
System.out.println("Multiple objects given: " + Arrays.toString(objs));
}
}
我得到其中 someMethod(Object[] objs)
被选择为 int[]
的输出:
Single object given: [I@140e19d
我在尝试记录一些消息时遇到了这样的行为:
logger.log(Level.INFO, "param1: {0}, param2: {1}", new int[] {1, 2});
输出:
...
INFO: param1: [I@103dbd3, param2: {1}
那么为什么选择Object而不是Object[]作为原始数组的方法参数呢?
因为 int[]
不是 Object[]
- 就这么简单。 Object[]
的元素必须是引用 - int[]
的元素是 而不是 引用。
JLS section 4.10.3 讨论数组的子类型关系 - 特别是:
If
S
andT
are both reference types, thenS[] >1 T[]
iffS >1 T
.