varargs 和 '...' 参数 [英] varargs and the '...' argument
问题描述
考虑方法声明:
String.format(String, Object ...)
Object ...
参数只是对 Object
数组的引用.有没有办法通过引用实际的Object
数组来使用这个方法?如果我将一个Object
数组传递给...
参数 - 结果参数值是否是一个二维数组 - 因为 Object[]
本身就是一个 Object
:
The Object ...
argument is just a reference to an array of Object
s. Is there a way to use this method with a reference to an actual Object
array? If I pass in an Object
array to the ...
argument - will the resultant argument value be a two-dimensional array - because an Object[]
is itself an Object
:
Object[] params = ....; // Make the array (for example based on user-input)
String s = String.format("%S has %.2f euros", params);
所以数组的第一个组件(在 String.format
方法中使用)将是一个数组,他将生成:
So the first component of the array (Which is used in the String.format
method), will be an array and he will generate:
[class.getName() + "@" + Integer.toHexString(hashCode())]
然后错误,因为数组大小为 1.
and then an error because the array size is 1.
粗体序列才是真正的问题.
这是第二个问题:...
数组/参数是否有名称?
The bold sequence is the real question.
This is a second question: Does a ...
array/parameter have a name?
推荐答案
来自 关于可变参数的文档:
决赛后的三个时期参数的类型表明最终参数可以作为数组或作为参数序列.
The three periods after the final parameter's type indicate that the final argument may be passed as an array or as a sequence of arguments.
所以你可以传递多个参数或一个数组.
So you can pass multiple arguments or an array.
以下工作正常:
class VarargTest {
public static void main(String[] args) {
Object[] params = {"x", 1.2345f};
String s = String.format("%s is %.2f", params);
System.out.println(s); // Output is: x is 1.23
}
}
这篇关于varargs 和 '...' 参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!