美文网首页
关于整型包装类值的比较

关于整型包装类值的比较

作者: 画个圈写个喵 | 来源:发表于2020-08-26 23:57 被阅读0次

    所有整型包装类对象值的比较必须使用equals方法。

    /****************自动装箱的方式创建Integer  begin******************/
    Integer a1 =3;
    
    Integer a2 =3;
    
    System.out.println(a1 == a2); // true
    
    System.out.println(a1.equals(a2)); // true
    
    
    Integer b1 =128;
    
    Integer b2 =128;
    
    System.out.println(b1 == b2); // false
    
    System.out.println(b1.equals(b2)); // false
    /****************自动装箱的方式创建Integer   end******************/
    
    
    Integer c1 =new Integer(3);
    
    Integer c2 =new Integer(3);
    
    System.out.println(c1 == c2); // false
    
    System.out.println(c1.equals(c2)); // true
    
    Integer d1 =new Integer(128);
    
    Integer d2 =new Integer(128);
    
    System.out.println(d1 == d2); // false
    
    System.out.println(d1.equals(d2)); // true
    

    当使用自动装箱方式创建一个Integer对象时,当数值在-128 ~127时,会将创建的 Integer 对象缓存起来,当下次再出现该数值时,直接从缓存中取出对应的Integer对象。所以上述代码中,a1和a2引用的是相同的Integer对象,此时 a1==a2是相同的地址进行比较,返回true
    而b1和b2虽然也是通过自动装箱的方式创建,但由于数值为128不在-128~127之间,因此该值不会被缓存,每次都会创建一个新的Integer对象;所以==判断为false,equals判断为true


    补充:

    == : 它的作用是判断两个对象的地址是不是相等。即,判断两个对象是不是同一个对象(基本数据类型==比较的是值,引用数据类型==比较的是内存地址)。
    equals() : 它的作用也是判断两个对象是否相等。但它一般有两种使用情况:

    • 情况 1:类没有覆盖 equals() 方法。则通过 equals() 比较该类的两个对象时,等价于通过“==”比较这两个对象。
    • 情况 2:类覆盖了 equals() 方法。一般,我们都覆盖 equals() 方法来比较两个对象的内容是否相等;若它们的内容相等,则返回 true (即,认为这两个对象相等)。\color{red}{equals 方法被覆盖过, hashCode 方法也必须被覆盖}

    相关文章

      网友评论

          本文标题:关于整型包装类值的比较

          本文链接:https://www.haomeiwen.com/subject/txsqsktx.html