Java包装类

包装类学习笔记

  • 为什么需要包装类
    • Java是一门面向对象的语言而八种基本数据类型却不是面向对象的为了使用方便我们需要把他们转化成对象例如用集合来存八种基本数据类型的时候就需要将其转化为对象
  • 八种基本数局类型byte short int long char float double boolean对应的包装类
    • byte : Byte
    • short : Short
    • int : Integer
    • long : Long
    • char : Character
    • float : Float
    • double : Double
    • boolean : Boolean
  • 使用语法这里以int为例其他7种一样
    • Integer it =new Integer(123);
    • Integer it =Integer.valueOf(123);
  • JDk1.5版本以后就有了自动装箱和拆箱具体如下还是以int的包装类举例
    • 自动装箱 Integer it =123;这里的自动装箱其实是伪自动装箱实际在编译时自动给我们添加了底层实现Integer it =Integer.valueOf(123);
    • 自动拆箱 Integer it = new Integer(123);
      • int a =it;
      • 这里的自动拆箱也是伪自动拆箱底层实际是int a=it.intValue();

包装类的自动装箱有一个需要注意的地方是包装类的缓存,以为例Integer,Integer的源码 中有一个数组里面存着-128127对应的包装类也就是-28127之间的数字是有缓存的当我们创建-128127之间的包装类时会自动从数组里面取相应的对象而不会新创建对象,在-128127范围之外则会新创建一个对象

  • 例如:
    Integer it1 =-128;
    Integer it2 =-128;
    System.out.println(it1==it2);//==比较地址
    System.out.println(it1.equals(it2));//equals()比较值
    Integer it3 = 1234 ;
    Integer it4 = 1234;
    System.out.println(it3==it4);
    System.out.println(it3.euqals(it4));

  • 输出的结果为:

    • treu
    • true
    • false
    • true
  • 其他的包装类缓存:

    • Boolean:(全部缓存)
    • Byte:(全部缓存-12~127缓存)
    • Character(<= 127缓存)
    • Short(-128 ~ 127缓存)
    • Long(-128 ~127缓存)
    • Float(没有缓存)
    • Doulbe(没有缓存)
posted @ 2019-07-28 00:29  键盘敲坏  阅读(176)  评论(0)    收藏  举报