[java-intentions] IterateOverIterable: disable for empty lists and newly-created arrays (IJ-CR-8575)

GitOrigin-RevId: 78ef76ab85b1e051d0bb887801379136be041c5b
This commit is contained in:
Tagir Valeev
2021-05-11 12:00:19 +00:00
committed by intellij-monorepo-bot
parent 886acd3667
commit a9069f60e8
5 changed files with 38 additions and 0 deletions
@@ -35,6 +35,7 @@ import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.refactoring.util.CommonRefactoringUtil;
import com.intellij.util.IncorrectOperationException;
import com.siyeh.ig.psiutils.ConstructionUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -86,6 +87,14 @@ public class IterateOverIterableIntention implements IntentionAction {
}
PsiExpression expression = getIterableExpression(editor, file);
if (expression == null) return false;
if (ConstructionUtils.isEmptyCollectionInitializer(expression)) {
// Empty collection: iterating doesn't make much sense
return false;
}
if (expression instanceof PsiNewExpression && ((PsiNewExpression)expression).getArrayDimensions().length > 0) {
// new array without initializers: all elements are 0/null/false, so iterating doesn't make much sense
return false;
}
myText = JavaBundle.message("intention.name.iterate.over", Objects.requireNonNull(expression.getType()).getPresentableText());
return true;
}
@@ -0,0 +1,9 @@
// "Iterate over String[]" "true"
class Test {
void foo() {
for (String s : new String[]{"a", "b", "c"}) {
}
}
}
@@ -0,0 +1,8 @@
// "Disable 'Iterate'" "false"
import java.util.*;
class Test {
void foo() {
new ArrayList<><caret>();
}
}
@@ -0,0 +1,6 @@
// "Disable 'Iterate'" "false"
class Test {
void foo() {
new String<caret>[10];
}
}
@@ -0,0 +1,6 @@
// "Iterate over String[]" "true"
class Test {
void foo() {
new String<caret>[] {"a", "b", "c"};
}
}