user7198896
user7198896

Reputation:

Why does putting a multidimensional array in varargs cause a compiler warning?

I have a very simple not null checker that has a varargs parameter of type Object

public static void nonNull(Object... objects) { //... }

When I call it with a multidimensional array of any type, like:

nonNull(new int[][] {})

or

nonNull(new Object[][] {})

it results in a compiler warning saying "Inexact type match for varargs". it also happens for more than 2 dimensional arrays.

The warning doesn't appear for examples:

nonNull(new Object[] {})

or

nonNull(new Object())

I was just curious why. A multidimensional array is just another object just like a regular array isn't it? So why is the type match inexact?

Upvotes: 2

Views: 258

Answers (1)

user2357112
user2357112

Reputation: 280335

If you provide a single Object[] to your varargs method, it will be used as the objects argument directly rather than being wrapped in a length-1 array.

Both new int[][]{} and new Object[][]{} technically count as being of type Object[], due to array covariance.

Thus, for both nonNull(new int[][] {}) and nonNull(new Object[][] {}), the array you provided will be used as objects directly, rather than being passed as the sole element of a length-1 Object[].

It's pretty likely that you didn't want that to happen, so Java is giving you a warning about it.

Upvotes: 1

Related Questions