Sensei Logo Sensei Hub

Recipe - Incorrect use of Objects.equals

Description:
Comparing a non-unboxable object and a primitive will always return false
Level:
warning
Language:
  • java
Tags:
  • Java basic
  • quality
Documentation

Objects.equals will always return false when comparing a primitive type to an object type that is not a wrapper type.

Before
Object o = new Object(); // Not a wrapper type
boolean sameNumber = Objects.equals(o, 1);
boolean sameNumber = Objects.equals(1, o);
After
Object o = new Object(); // Not a wrapper type
boolean sameNumber = false;
boolean sameNumber = false;
Recipe
id: scw:java:equality-object-primitive
version: 10
metadata:
  name: Incorrect use of Objects.equals
  shortDescription: Comparing a non-unboxable object and a primitive will always return false
  level: warning
  language: java
  scwCategory: blog:generic
  cweCategory: 480
  enabled: true
  descriptionFile: descriptions/Incorrect_use_of_Objects.equals.html
  tags: Java basic;quality
search:
  methodcall:
    name: equals
    anyOf:
    - args:
        1:
          type:
            not:
              reference:
                matches: java\.lang\.(Boolean|Byte|Character|Float|Integer|Long|Short|Double)
              checkInheritance: true
            checkInheritance: true
            isPrimitive: false
        2:
          type:
            reference:
              not: '{{{ arguments.0.type }}}'
            checkInheritance: true
            isPrimitive: true
    - args:
        1:
          type:
            reference:
              not: '{{{ arguments.1.type }}}'
            checkInheritance: true
            isPrimitive: true
        2:
          type:
            not:
              reference:
                matches: java\.lang\.(Boolean|Byte|Character|Float|Integer|Long|Short|Double)
              checkInheritance: true
            checkInheritance: true
            isPrimitive: false
    type: Objects
availableFixes:
- name: Simplify to false
  actions:
  - rewrite:
      to: "false"