简体   繁体   中英

How to pass an array of primitives as varargs?

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

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();

You can use the wrapper class Integer instead, ie

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

This is how you would cast an existing int[] array:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM