int和Integer的理解和区别

int 和Integer的区别和联系

int:

  1. int是八种基本类型之一(byte,short,int,long,double,flout,boolean,char);
  2. int默认值是0;
  3. int比较的是两个值是否相等;

Integer:

  1. Integer是int的包装类,自动拆箱为int,提供了一系列的方法供调用,如字符串转换数字Integer.parseInt();
  2. Integer默认值是null;
  3. Integer是引用类型,比较的是内容地址是否相等;

关于int和Integer的比较:

  1. 基础比较

    int a = 12;
    int b = 12;
    boolean abCompare = (a==b); //基本类型比较的是值,true
    Integer c=12;//常量池
    
    Integer d = new Integer(12);//堆
    Integer e = new Integer(12);//堆
    boolean deCompare=(d==e);//直接相等比较值是false;
    boolean deEuqal=(d.equals(e));//equals比较的是引用地址true;
    
  2. Integer和int的拆装箱比较

     //int和Integer比较时候,会自动拆箱转换为int.其实就是两个int值进行比较
     int f =12324;
     Integer ff=12324;
     Integer fff=new Integer(12324);
     System.out.println(f==ff);//true
     System.out.println(f==fff);//true
    
  3. Integer特殊比较。Integer有个缓存区[-128,127],如是这个范围之内,会从缓存查询,否则new个新值。

    valueOf()函数源码

    	static final int low = -128;
    	static final int high;//静态代码块默认赋值127;
         /**
         *
         **/
    	public static Integer valueOf(int i) {
    		
            if (i >= IntegerCache.low && i <= IntegerCache.high)
                return IntegerCache.cache[i + (-IntegerCache.low)];
            return new Integer(i);
        }
    
        Integer aa =127;
        Integer aaa =127;
        System.out.println(aa==aaa);//true 查询是缓存
        Integer bb =128;
        Integer bbb =128;
        System.out.println(bb==bbb);//false new了一个新的。
    

自己的一点点总结,记录与2020年5月4日。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值