Reputation: 3412
I have a method which has a varargs parameter. It looks like this:
public void sampleFunction(String name, Object... args) {
}
I want to pass a byte[]
to this method, but as a single parameter. How can I do this?
byte[] myByteArray = functionReturningAByteArray();
sampleFunction("Name", myByteArray);
Will this be considered as an array or, will myByteArray
is considered as a single object?
When I passed the byte[]
, IntelliJ reports it as Confusing primitive array argument to varargs method
. I tried to cast myByteArray
to an Object
as it suggested, then it reports it as redundant cast.
I want to pass it as a single object.
Upvotes: 1
Views: 1024
Reputation: 393841
A byte[]
is a primitive array, so it is definitely not an Object[]
. Therefore, it will be passed as a single Object
instance to your vararg method.
If, on the other hand, you would pass a Byte[]
array, it will be passed as multiple Object
arguments to the vararg method.
Of course, you can verify this for yourself:
public static void sampleFunction(String name, Object... args) {
System.out.println (args.length);
}
sampleFunction("x", new byte[] {1,2,3});
sampleFunction("x", new Byte[] {1,2,3});
The first call prints 1
, while the second call prints 3
.
Upvotes: 5