Arrays.fill(Object[], Object) called with incompatible types.


The problem

Arrays.fill(Object[], Object) is used to copy a reference into every slot of an array.

For example:

String[] foo = new String[42];
Arrays.fill(foo, "life");
// 42 references to the same String instance of "life" in the foo array

However, because of Array covariance (e.g.: String[] is assignable to Object[]), and the signature of Arrays.fill is Arrays.fill(Object[], Object), this also allows you to do the following:

String[] foo = new String[42];
Arrays.fill(foo, 42); // ArrayStoreException! Integer can't be put into a String[]

This check detects the above circumstances, and won’t let you attempt to put Integers into a String[].

What about Lists?

List<T> doesn’t have the same issue, since generic types are not covariant.

List<String> foo = new ArrayList<>();
foo.add(42); // Compile time error: Integer is not assignable to String


Suppress false positives by adding the suppression annotation @SuppressWarnings("ArrayFillIncompatibleType") to the enclosing element.