如何将基元数组作为可变参数传递?

How to pass an array of primitives as varargs?

我一直在尝试将基元数组(在我的例子中是 int[])传递给具有可变参数的方法。

假设:

    // prints: 1 2
    System.out.println(String.format("%s %s", new String[] { "1", "2"}));
    // fails with java.util.MissingFormatArgumentException: Format specifier '%s'
    System.out.println(String.format("%s %s", new int[] { 1, 2 }));

但是请注意,第一行收到以下警告:

Type String[] of the last argument to method format(String, 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.

另请注意,我没有使用构造函数输入数组,而是从封闭方法中获取它,我无法更改其签名,例如:

private String myFormat(int[] ints) {
    // whatever format it is, it's just an example, assuming the number of ints
    // is greater than the number of the format specifiers
    return String.format("%s %s %s %s", ints);
}

您可以改用包装器 class Integer,即

System.out.println(String.format("%s %s", new Integer[] { 1, 2 }));

这是转换现有 int[] 数组的方式:

int[] ints = new int[] { 1, 2 };

Integer[] castArray = new Integer[ints.length];
for (int i = 0; i < ints.length; i++) {
    castArray[i] = Integer.valueOf(ints[i]);
}

System.out.println(String.format("%s %s", castArray));

String.format(String format, Object... args) 正在等待 Object 可变参数作为参数。由于 int 是原始类型,而 Integer 是 java Object,您确实应该将 int[] 转换为 Integer[].

如果你在 Java 7 或者 Java 8,你可以使用 nedmund answer 来做到这一点,你可以一行:

Integer[] what = Arrays.stream( data ).boxed().toArray( Integer[]::new );

或者,如果您不需要 Integer[],如果 Object[] 足以满足您的需要,您可以使用:

Object[] what = Arrays.stream( data ).boxed().toArray();

int 可变参数到对象可变参数,创建一个带有空白分隔符的格式化程序

 private void method( int ... values) {
        String.format(StringUtils.repeat("%d", " ", values.length),  Arrays.stream( values ).boxed().toArray());
 }