java——装包与拆包

JAVA给简单类型都提供了对应的类类型(包装类型)

  byte           Byte
  char           Character
  short          Short
  int            Integer
  long           Long
  float          Float
  double         Double
  boolean        Boolean
  void           Void

总结:

  1. int 和Integer在进行比较的时候,Integer会进行拆箱,转为int值与int进行比较。
  2. Integer与Integer比较的时候,由于直接赋值的时候会进行自动的装箱,需要注意两个问题,一个是-128<= x<=127的整数,将会直接缓存在IntegerCache中,当赋值在这个区间的时候,不会创建新的Integer对象,而是从缓存中获取已经创建好的Integer对象。二是当大于这个范围的时候,直接new Integer来创建Integer对象。
    例如:
    new Integer(1) 和Integer a = 1不同,前者会创建对象,存储在堆中,而后者因为在-128到127的范围内,不会创建新的对象,而是从IntegerCache中获取的。那么Integer a = 128, 大于该范围的话才会直接通过new Integer(128)创建对象,进行装箱。

Integer中的装箱的代码

public static Integer valueOf(int i){
      if(i>=IntegerCache.low && i<=IntegerCache.high){
             return IntegerCache.cache[i+(-IntegerCache.low)];
             }
       return new Integer(i);
       }

代码测试:

package com.example;
public class MainTestDemo {
    public static void main(String[] args) {
//简单类型定义的变量,内存都在函数栈上
//引用变量都在函数栈上存储,但是存储的只是对象的引用(堆上的地址)
        Integer int1=10;               //栈上
        Integer int2=new Integer(10);  //堆上
        if(int1==int2){    
            System.out.println("int1==int2");
        }else{
            System.out.println("int1!=int2");
        }

        Integer int3=new Integer(10);   //new的时候在堆中重新分配存储空间,int2和int3存储的堆上的地址不一样
        if(int2==int3){
            System.out.println("int2==int3");
        }else{
            System.out.println("int2!=int3");
        }

        Integer int4=new Integer(200);  //分配的地址不同
        Integer int5=new Integer(200);
        if(int4==int5){
            System.out.println("int4==int5");
        }else{
            System.out.println("int4!=int5");
        }

        Integer int6=127;
        Integer int7=127;//Integer int7=int6;
        if(int6==int7){
            System.out.println("int6==int7");
        }else{
            System.out.println("int6!=int7");
        }
        //i6、i7是自动装箱产生的对象,其值都是127,127正好在-128<=i7<=127
        //这个范围内的,那么会去IntegerCache中取,该对象应该是一个对象,在堆中的
        //地址应该是一样的,所以在判断两个对象是不是==的时候,会输出相等。
        Integer int8=128;
        Integer int9=128;
        if(int8==int9){
            System.out.println("int8==int9"); 
        }else{
            System.out.println("int8!=int9");
        }
        //i8和i9是自动装箱产生的Integer的对象,但是其大小超过了范围:-128<=A <=127,
        //这里会直接自己创建该对象即:new Integer(128);显然这两个对象都是new出来,
        //在堆中的地址值是不同的,所以二者不相等。

    }
}

这里写图片描述
注:
Byte、Float、Double没有缓存;
Integer、Short、Long的缓存范围都是[-128,127];
Character的缓存范围是[0,127].

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值