Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -64,21 +64,31 @@ private static class ReplaceCollectionToArrayArgWithEmptyArrayVisitor<P> extends

@Override
public J.NewArray visitNewArray(J.NewArray newArray, P p) {
if (COLLECTION_TO_ARRAY.advanced().isFirstArgument(getCursor()) && newArray.getDimensions().size() == 1) {
boolean isInitializerEmpty = newArray.getInitializer() == null
|| (newArray.getInitializer().size() == 1 && newArray.getInitializer().get(0) instanceof J.Empty);
if (COLLECTION_TO_ARRAY.advanced().isFirstArgument(getCursor()) && isInitializerEmpty) {
J.NewArray newArrayZero = newArray.withDimensions(ListUtils.mapFirst(newArray.getDimensions(), d -> {
if (d.getIndex() instanceof J.Literal && Integer.valueOf(0).equals(((J.Literal) d.getIndex()).getValue())) {
return d;
}
JavaType.Primitive type;
if (d.getIndex() instanceof J.Empty) {
type = JavaType.Primitive.Int;
} else {
type = (JavaType.Primitive) requireNonNull(d.getIndex().getType());
}

return d.withIndex(new J.Literal(
Tree.randomId(),
Space.EMPTY,
Markers.EMPTY,
0,
"0",
emptyList(),
(JavaType.Primitive) requireNonNull(d.getIndex().getType())
type
));
}));
newArrayZero = newArrayZero.withInitializer(null);
return maybeAutoFormat(newArray, newArrayZero, p);
}
return super.visitNewArray(newArray, p);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,4 +83,49 @@ void test(Collection<Integer> args){
)
);
}

@Test
void replaceEmptyArrayInitializerWithZero() {
rewriteRun(
//language=java
java(
"""
import java.util.Collection;

class A {
void test(Collection<Integer> args){
Integer[] array = args.toArray(new Integer[]{});
}
}
""",
"""
import java.util.Collection;

class A {
void test(Collection<Integer> args){
Integer[] array = args.toArray(new Integer[0]);
}
}
"""
)
);
}

@Test
void dontChangeNonEmptyInitializer() {
rewriteRun(
//language=java
java(
"""
import java.util.Collection;

class A {
void test(Collection<Integer> args){
Integer[] array = args.toArray(new Integer[]{1, 2, 3});
}
}
"""
)
);
}
}