java包装类型的一些知识点

关键字:包装类的缓存,包装类之间数值的比较

来源:https://www.cnblogs.com/hdwang/p/7009449.html

https://www.cnblogs.com/DreamDrive/p/5422761.html

https://blog.csdn.net/wxy941011/article/details/80768271

1.

1.System.out.println(127==127); //true , int type compare
2.System.out.println(128==128); //true , int type compare
3.System.out.println(new Integer(127) == new Integer(127)); //false, object compare
4.System.out.println(Integer.parseInt("128")==Integer.parseInt("128")); //true, int type compare
5.System.out.println(Integer.valueOf("127")==Integer.valueOf("127")); //true ,object compare, because IntegerCache return a same object
6.System.out.println(Integer.valueOf("128")==Integer.valueOf("128")); //false ,object compare, because number beyond the IntegerCache
7.System.out.println(Integer.parseInt("128")==Integer.valueOf("128")); //true , int type compare

解释

int整型常量比较时,== 是值比较,所以1,2返回true。1,2是值比较。

new Integer() 每次构造一个新的Integer对象,所以3返回false。3是对象比较。

Integer.parseInt每次构造一个int常量,所以4返回true。4是值比较。

Integer.valueOf返回一个Integer对象,默认在-128~127之间时返回缓存中的已有对象(如果存在的话),所以5返回true,6返回false。5,6是对象比较。

第7个比较特殊,是int 和 Integer之间的比较,结果是值比较,返回true。

总结

对于整型的比较,首先判断是值比较还是对象比较,值比较肯定返回true,有一个是值就是值比较。对象比较,则看对象是怎么构造出来的,如果是采用new Integer方式,则每次产生新对象,两个new出来的Integer比较肯定返回false,如果是Integer.valueOf方式的话,注意值的区间是否在-128~127之间,如果在,则构造的相同值的对象是同一个对象,==比较后返回true,否则返回false。

所以,对于值比较==放心没问题,对于Integer的比较最好用equals方法比较对象内容,当然注意先判断Integer是否不为null。

2.

public class Client {
    public static void main(String[] args) {
        Integer a = new Integer(100);
        Integer b = new Integer(100);
        /* compareTo返回值:若a>b则返回1;若a==b则返回0;若a<b则返回-1 */
        int result = a.compareTo(b);

        System.out.println(a > b);
        System.out.println(a == b);
        System.out.println(a > b);
        System.out.println(result);
    }
}

运行结果:

false
false
false
0

为什么(a==b)返回值会是false呢?

通过对比字符串比较来理解,基本类型100通过包装类Integer包装后生产一个Integer对象的引用a,
而“==”使用来判断两个操作数是否有相等关系。如果是基本类型就直接判断其值是否相等。
若是对象就判断是否是同一个对象的引用,显然我们new了两个不同的对象。
但注意:
对于"<",">" 只是用来判断两个基本类型的数值的大小关系。在进行(a<b)运算时,

实际上是根据其intValue方法的返回对应的数值来进行比较的。因此返回肯定是false.

知道问题原因,解决起来就容易了。两种方法:
第一种: a.intValue()==b.intValue();
第二种: a.compareTo(b);//返回-1代码(a<b),返回0代表(a==b),返回1代表(a>b)
第二种方法源码如下:

1 public int compareTo(Integer object) {
2     int thisValue = value;
3     int thatValue = object.value;
4     return thisValue < thatValue ? -1 : (thisValue == thatValue ? 0 : 1);
5 }

由此可知,底层实现还是一样的。

3.

包装器的缓存:

  • boolean:(全部缓存)
  • byte:(全部缓存)
  • character(<= 127缓存)
  • short(-128 — 127缓存)
  • long(-128 — 127缓存)
  • integer(-128 — 127缓存)
  • float(没有缓存)
  • doulbe(没有缓存)
原文地址:https://www.cnblogs.com/bbllw/p/10076460.html