考虑方法声明:
String.format(String, Object ...)
Object ...
参数只是对 Object
数组的引用。 有没有办法将此方法与实际 Object
数组的引用一起使用? 如果我将 Object
数组传递给 ...
参数 - 结果参数值将是一个二维数组 - 因为 Object[]
本身就是一个 Object
:
Object[] params = ....; // Make the array (for example based on user-input)
String s = String.format("%S has %.2f euros", params);
所以数组的第一个组件(在 String.format
方法中使用)将是一个数组,他将生成:
[class.getName() + "@" + Integer.toHexString(hashCode())]
然后出现错误,因为数组大小为 1。
粗体序列才是真正的问题。
这是第二个问题:...
数组/参数有名称吗?
最佳答案
来自 docs on varargs :
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.
所以你可以传递多个参数或一个数组。
以下工作正常:
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
}
}
关于java - 可变参数和 '...' 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1656901/