diff --git a/java/java-impl/src/com/intellij/codeInspection/CollectionAddAllCanBeReplacedWithConstructorInspection.java b/java/java-impl/src/com/intellij/codeInspection/CollectionAddAllCanBeReplacedWithConstructorInspection.java index c0f51c9ade03..737975372436 100644 --- a/java/java-impl/src/com/intellij/codeInspection/CollectionAddAllCanBeReplacedWithConstructorInspection.java +++ b/java/java-impl/src/com/intellij/codeInspection/CollectionAddAllCanBeReplacedWithConstructorInspection.java @@ -95,7 +95,7 @@ public class CollectionAddAllCanBeReplacedWithConstructorInspection extends Base } PsiLocalVariable variable = (PsiLocalVariable)resolvedReference; final PsiType variableType = variable.getType(); - if (!(variableType instanceof PsiClassType)) { + if (!(variableType instanceof PsiClassType) || statementHasSubsequentAddAll(parent, variable, methodName)) { return; } final PsiClass variableClass = ((PsiClassType)variableType).resolve(); @@ -130,6 +130,26 @@ public class CollectionAddAllCanBeReplacedWithConstructorInspection extends Base }; } + private static boolean statementHasSubsequentAddAll(@NotNull PsiElement statement, + @NotNull PsiLocalVariable referent, + @NotNull String previousMethodName) { + final PsiElement sibling = PsiTreeUtil.getNextSiblingOfType(statement, PsiStatement.class); + if (sibling instanceof PsiExpressionStatement) { + final PsiExpression siblingExpression = ((PsiExpressionStatement)sibling).getExpression(); + if (siblingExpression instanceof PsiMethodCallExpression) { + final PsiMethodCallExpression siblingMethodCall = (PsiMethodCallExpression)siblingExpression; + final PsiExpression qualifier = siblingMethodCall.getMethodExpression().getQualifierExpression(); + if (qualifier instanceof PsiReferenceExpression && referent.isEquivalentTo(((PsiReferenceExpression)qualifier).resolve())) { + final PsiMethod method = siblingMethodCall.resolveMethod(); + if (method != null && method.getName().equals(previousMethodName)) { + return true; + } + } + } + } + return false; + } + private boolean checkLocalVariableAssignmentOrInitializer(PsiExpression initializer) { if (!(initializer instanceof PsiNewExpression)) { return false; diff --git a/java/java-tests/testData/inspection/collectionAddAllCanBeReplacedWithConstructor/beforeSequentalAddAllExists.java b/java/java-tests/testData/inspection/collectionAddAllCanBeReplacedWithConstructor/beforeSequentalAddAllExists.java new file mode 100644 index 000000000000..7340e9653f95 --- /dev/null +++ b/java/java-tests/testData/inspection/collectionAddAllCanBeReplacedWithConstructor/beforeSequentalAddAllExists.java @@ -0,0 +1,12 @@ +// "Replace 'addAll/putAll' method with parametrized constructor call" "false" +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +class A { + void m(String s) { + final List list = new ArrayList<>(); + list.addAll(Arrays.asList(s, ",")); + list.addAll(Arrays.asList(s, ",")); + } +} \ No newline at end of file