可变参数和'...'的说法 [英] varargs and the '...' argument

查看:81
本文介绍了可变参数和'...'的说法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑方法声明:

String.format(String, Object ...)

对象... 参数只是以对象秒的数组的引用。 有没有使用此方法的引用到实际对象的方式数组?如果我通过在一个对象阵列到 ... 参数 - 将所得到的参数值是一个二维数组 - 因为对象[] 本身就是一个对象

The Object ... argument is just a reference to an array of Objects. 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.

我希望我已经解释好。可能很多语法错误(14岁,荷兰人说),所以请原谅我。

I hope I have explained well. Probably a lot grammar faults (14 years old and Dutch speaking), so forgive me.

粗体序列是真正的问题。结果
这是第二个问题:?做了 ... 阵列/参数有一个名字

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
  }
}

这篇关于可变参数和'...'的说法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆