Integer Cache

 

整形是基础数据类型的一种,int也有自己的包装类Integer.但是如何比较两个整形呢.

public static void main(String[] args) {
    Integer a = 1;
    Integer b = 1;
    int c = 1;

    Integer a1 = 256;
    Integer b1 = 256;
    int c1 = 256;

    System.out.println(a == b);
    System.out.println(a == c);
    System.out.println(b == c);
    System.out.println(a1.equals(b1));
    System.out.println(a1 == b1);
    System.out.println(a1 == c1);
    System.out.println(b1 == c1);
}

输出

true
true
true
true
false
true
true

 

这是因为 对于-127-128的整形,在创建包装类的时候会直接从缓存好的IntegerCache中取,所以此时用 == 会为true,但是超过这个范围就会false.

但是包装类和int比较的时候,会自动拆箱,只会比较数字.

还有一个比较火的题,这里就要用反射去改变值了.可以参考下https://www.jianshu.com/p/0f8fa37b13bd

  //要求写一个swap方法交换ab值输出打印a=2 b=1
    public static void main(String[] args) {
        Integer a=1,b=2;
        swap(a,b);
        System.out.println("a="+a+"   b="+b);
    }

    private static void swap1(Integer aa, Integer bb) {
        try {
            Field aaValue = aa.getClass().getDeclaredField("value");
            aaValue.setAccessible(true);
            aaValue.set(aa,2);
            Field bbValue = bb.getClass().getDeclaredField("value");
            bbValue.setAccessible(true);
            //这里的1不会自动装箱,当然就不会从缓存中去取值
            bbValue.set(bb,new Integer(1));
        } catch (Exception e) {
            e.printStackTrace();
        }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值