关于Java Integer和Long使用equals直接比较

Integer和Long不能直接equals比较会返回False

Long.class源码

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

Integer.class源码

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

解决方法

  • Long变量.equals(Integer变量.longValue())
  • Integer变量.equals(Long变量.intValue())

猜你喜欢

转载自blog.csdn.net/weixin_46099269/article/details/133937268