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, i.e.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With