This rule raises an issue when a local variable declaration or a field declaration uses an array initializer preceded by an explicit array creation expression whose type is the same as the declared type.
When an array variable or field is declared and initialized in the same statement, Java allows the array initializer to stand on its own:
int[] delays = {100, 500, 2000};. Writing an explicit array creation expression in front of it, as in int[] delays = new int[]
{100, 500, 2000};, repeats the element type and the array-ness that the declaration on the left already states.
The line then carries the same type information twice and pushes the values, the only part that actually differs between two such declarations, further to the right. In a class holding several constant arrays, this repetition makes the declarations harder to scan and to compare.
Both forms compile to the same bytecode, so dropping the redundant new <type>[] prefix changes nothing at runtime.
To fix it, delete the new <type>[] prefix and keep the curly-brace initializer alone.
The shorthand initializer is only legal in a declaration. Everywhere else the explicit array creation expression is mandatory, so no issue is raised on:
delays = new int[] {100, 500};handler.accepts(new String[] {"GET", "HEAD"});return new int[] {0};List.of(new String[] {"a", "b"});Annotation element values are not concerned: they already require the shorthand, because an array creation expression is not a constant expression and the compiler rejects it there.
No issue is raised either when the created type differs from the declared type, because dropping the prefix would change the runtime type of the array:
Object[] values = new String[] {"GET", "HEAD"};
Declarations using var are not reported, since var values = {1, 2}; does not compile: an array initializer carries no
type of its own and var needs one.
A created type carrying a type annotation is not reported either, as in String[] names = new @Marker String[] {"GET"};. The shorthand
form has nowhere to put the annotation, so dropping the prefix would silently discard it.
Remove the new <type>[] part that sits between the = sign and the opening brace, and leave the initializer as is.
The number and the order of the elements stay untouched, and the declared type on the left keeps driving the type of the created array, so the fix
preserves behavior.
public class HttpDefaults {
private static final String[] SAFE_METHODS = new String[] {"GET", "HEAD", "OPTIONS"}; // Noncompliant
public int retryDelay(int attempt) {
int[] delays = new int[] {100, 500, 2000}; // Noncompliant
return delays[Math.min(attempt, delays.length - 1)];
}
}
public class HttpDefaults {
private static final String[] SAFE_METHODS = {"GET", "HEAD", "OPTIONS"};
public int retryDelay(int attempt) {
int[] delays = {100, 500, 2000};
return delays[Math.min(attempt, delays.length - 1)];
}
}