About direct comparison between Java Integer and Long using equals

Integer and Long cannot be directly compared with equals and will return False.

Long.class source code

public boolean equals(Object obj) {
    
    
    if (obj instanceof Long) {
    
    
        return this.value == (Long)obj;
    } else {
    
    
        return false;
    }
}

Integer.class source code

public boolean equals(Object obj) {
    
    
    if (obj instanceof Integer) {
    
    
        return this.value == (Integer)obj;
    } else {
    
    
        return false;
    }
}

Solution

  • Long variable.equals(Integer variable.longValue())
  • Integer variable.equals(Long variable.intValue())

Guess you like

Origin blog.csdn.net/weixin_46099269/article/details/133937268