[java-inspections] RedundantCompareCall: insert cast when both operands are boxed

Fixes IDEA-291826 IntelliJ Suggest simplify Integer.compare method to `==`

GitOrigin-RevId: 71882cec49e2846f0b30ae626da6d07381e516e2
This commit is contained in:
Tagir Valeev
2022-04-22 10:57:04 +00:00
committed by intellij-monorepo-bot
parent 340a56e8af
commit 35711da1d7
3 changed files with 32 additions and 1 deletions
@@ -0,0 +1,10 @@
// "Fix all 'Redundant 'compare()' method call' problems in file" "true"
class Boxing {
void test(Integer x, Integer y, int z) {
boolean same = (int) x == y;
boolean same1 = x > y;
boolean same2 = (int) x != y;
boolean same3 = x == z;
boolean same4 = z == x;
}
}
@@ -0,0 +1,10 @@
// "Fix all 'Redundant 'compare()' method call' problems in file" "true"
class Boxing {
void test(Integer x, Integer y, int z) {
boolean same = Integer.<caret>compare(x, y) == 0;
boolean same1 = Integer.compare(x, y) > 0;
boolean same2 = Integer.compare(x, y) != 0;
boolean same3 = Integer.compare(x, z) == 0;
boolean same4 = Integer.compare(z, x) == 0;
}
}
@@ -70,10 +70,21 @@ public class RedundantCompareCallInspection extends AbstractBaseJavaLocalInspect
if (call == null) return;
PsiExpression[] args = call.getArgumentList().getExpressions();
if(args.length != 2) return;
String maybeCast = "";
if (myRelationType == RelationType.EQ || myRelationType == RelationType.NE) {
PsiType leftType = args[0].getType();
PsiType rightType = args[1].getType();
if (leftType instanceof PsiClassType && rightType instanceof PsiClassType) {
PsiPrimitiveType type = PsiPrimitiveType.getOptionallyUnboxedType(leftType);
if (type != null) {
maybeCast = "(" + type.getCanonicalText() + ")";
}
}
}
PsiBinaryExpression parent = PsiTreeUtil.getParentOfType(call, PsiBinaryExpression.class);
if (parent == null) return;
CommentTracker ct = new CommentTracker();
ct.replaceAndRestoreComments(parent, ct.text(args[0], ParenthesesUtils.EQUALITY_PRECEDENCE) +
ct.replaceAndRestoreComments(parent, maybeCast + ct.text(args[0], ParenthesesUtils.EQUALITY_PRECEDENCE) +
myRelationType +
ct.text(args[1], ParenthesesUtils.EQUALITY_PRECEDENCE));
}