This rule raises an issue when Arrays.fill() is called with an argument whose static type is incompatible with the component type of the array being filled.

Why is this an issue?

In Java, arrays are covariant: a String[] is considered an Object[] by the type system. Consequently, Arrays.fill(Object[] a, Object val) and its bounded range overload accept any Object value as the filling element. However, if the runtime component type of the array cannot hold the provided value, the Java Virtual Machine throws an ArrayStoreException at runtime.

Calling Arrays.fill(Object[] a, Object val) with a value whose type cannot be stored in the target array component type is guaranteed to fail at runtime. For example, attempting to fill a String[] with an Integer compiles without error because String[] is an Object[] and Integer is an Object. When executed, the method attempts to store each element into the array, which immediately throws an ArrayStoreException.

Similarly, passing a non-null object into an array of a distinct, incompatible class hierarchy causes an immediate runtime failure. This problem often arises after refactoring an array type without updating its initialization, or when accidentally confusing the fill value with an index or default value from another data structure.

How to fix it

Change the filling value to an instance that is compatible with the array component type, or change the target array type so that it can hold the intended value.

Code examples

Noncompliant code example

import java.util.Arrays;

class ArrayFillExample {
  void initializeBuffers() {
    String[] textBuffer = new String[10];
    Arrays.fill(textBuffer, 42); // Noncompliant: filling an array of type "String[]" with an "Integer" throws ArrayStoreException

    Integer[] numbers = new Integer[5];
    Arrays.fill(numbers, "default"); // Noncompliant: filling an array of type "Integer[]" with a "String" throws ArrayStoreException
  }
}

Compliant solution

import java.util.Arrays;

class ArrayFillExample {
  void initializeBuffers() {
    String[] textBuffer = new String[10];
    Arrays.fill(textBuffer, "default");

    Integer[] numbers = new Integer[5];
    Arrays.fill(numbers, 0);
  }
}

Resources

Documentation

Related rules