gpt4 book ai didi

java - 方法 println(Object...) 的最后一个参数的类型 int[][] 与可变参数类型不完全匹配

转载 作者:行者123 更新时间:2023-12-05 02:05:47 26 4
gpt4 key购买 nike

我有以下内容:


static public void println(Object what) {
if (what == null) {
out.println("null");
out.flush();
}
else if (what.getClass().isArray()) {
printlnArray(what);
}
else {
out.println(what);
out.flush();
}
}


static public void println(Object... variables) {

for (int i = 0; i < variables.length; i++) {
Object o = variables[i];
if (o.getClass().isArray()) {
printlnArray(o);
}
else {
out.print(o);
if (i != variables.length-1) out.print(" ");
}
}
out.println();
out.flush();
}

如果我这样调用它:

int[][] array_2d = {{1}, {1, 2}, {1, 2, 3}};
println("array_2d");
println(array_2d);

然后我得到错误:

Type int[][] of the last argument to method println(Object...) doesn't exactly match the vararg parameter type. Cast to Object[] to confirm the non-varargs invocation, or pass individual arguments of type Object for a varargs invocation.

我似乎找不到抑制此警告的方法。我也没有运气修复错误。添加 println(int[][] variables) 不是一个选项。

我做了这个方向的尝试:

enum Skip {
SKIP
}

static public void println(Object[] variables) {
println(Skip.SKIP, variables);
}

static public void println(Object first, Object... variables) {

if (first instanceof Skip) {

}
else {
print(first);
}

但它不起作用,需要大量晦涩的代码才能使其正常工作。

这个问题可以用合理干净的代码解决吗?

最佳答案

一个问题是对 println 的调用是不明确的。毕竟,println(Object... x) 只是 println(Object[] x) 的语法糖,调用者会默默地为您创建该数组如果使用多个参数调用。这使得用单个值调用 println,但该值是一个数组,是模棱两可的:任何一种形式都是合理的(数组本身就是一个对象!)

简单的解决方案是消除歧义:

/*1*/ public void println() {}

/*2*/ public void println(Object o) { ... }

/*3*/ public void println(Object a, Object b, Object... rest) { }

现在除了 println() 之外的所有形式都可以解决并且没有歧义:

println(); // invokes #1
println(x); // invokes #2, and only #2. Even if x is an array.
println(x, y); //invokes #3, with an empty array for 'rest'
println(x, y, a, b, c); // invokes #3.

注意:不要写 println(Object a, Object b)println(Object a, Object... rest) - 这会再次引起歧义!

关于java - 方法 println(Object...) 的最后一个参数的类型 int[][] 与可变参数类型不完全匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63131631/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com