How to pass an array of primitives as varargs?

maxxyme :

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);
}
minioim :

The String.format(String format, Object... args) is waiting an Object varargs as parameter. Since int is a primitive, while Integer is a java Object, you should indeed convert your int[] to an Integer[].

To do it, you can use nedmund answer if you are on Java 7 or, with Java 8, you can one line it:

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

or, if you don't need to have an Integer[], if an Object[] is enough for your need, you can use:

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

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=431437&siteId=1