I've been using Java's variable arguments in my methods, and have been testing them by passing in null as a parameter:
public void method(Object A, Object...b) {
if(A == null || b == null || b.length == 0) return;
...(something that invokes b)...
public void test() {
method(new Object(), null)
...
At the beginning of the method, I checked for null as the parameter, and even for the length to be 0. But since the test kept failing because of a NullPointerException
, I ran the debugger, and b
was length 1! It even said when I clicked on the disclosure triangle for b
,
all elements are null
I eventually resolved this by checking for length 1 and element 0 is null, but does anyone have an explanation for why Java does this? Thanks!
Because you're passing in a value of null
.
If you want your varargs method to receive an empty array, either
pass that explicitly:
method(new Object(), new Object[0])
don't pass anything at all:
method(new Object())
Option 2 would be more idiomatic.
null
is a value.
You provide a single value for the varargs argument, so the array will be new Object[] { null }
which has a length of 1.
If you wanted to pass no values at all, you'd have to call method(new Object());
.
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