How to pass an array of primitives as varargs?

Viewed 6002

I'm stuck trying to pass an array of primitives (in my case an int[]) to a method with varargs.

Let's say:

    // 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 }));

Note however that the first line gets the following warning:

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.

Note also I don't input the array with a constructor, but I get it from the enclosing method, whose signature I can't change, like:

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);
}
3 Answers

int varargs to object varargs, creating a formater with blank separator

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