zoukankan      html  css  js  c++  java
  • 两个值相同的Integer对象的比较

    package com.jj.test;
    
    import java.util.Objects;
    
    public class ObjectEqualsTest {
        public static final Integer COUNT_NONE = 0;
        public static void main(String[] args){
            Integer a=new Integer(0);
            boolean bool = Objects.equals(a,COUNT_NONE);
            a.equals(COUNT_NONE);
            System.out.println(a==COUNT_NONE);/*1*/
            System.out.println(bool);/*2*/
            System.out.println(a.equals(COUNT_NONE));/*3*/
        }
    }

    运行结果:

    false
    true
    true

    1.结果的第一行是false原因为:

    两个integer引用的地址不同,==比较的是引用(内存地址),所以最终结果是false。 

    2.通过源码可以很清楚的看到后两个结果是true的原因:

    Objects对象中equals方法的源码:

      public static boolean equals(Object a, Object b) {
            return (a == b) || (a != null && a.equals(b));
        }

    Integer对象中重写的Object.equals()方法:

    public boolean equals(Object obj) {
            if (obj instanceof Integer) {
                return value == ((Integer)obj).intValue();
            }
            return false;
        }
  • 相关阅读:
    poj 1026 Cipher
    python中的global
    基于DL的文本分类综述
    K近邻算法学习
    聚类评价指标学习
    pytorch自动求导学习
    反向传播的推导
    二分搜索常用【转载】
    《Attention is all you need》论文学习
    5-28日|5-30日
  • 原文地址:https://www.cnblogs.com/Allen-win/p/8059019.html
Copyright © 2011-2022 走看看