int和integer的比较

int和integer的区别:

  1. int是基本数据类型,Iteger是int的包装类(是一个对象)。
  2. Integer可能会创建一个新的空间,但int只是将数据存储在内存空间中。
  3. Integer和int不是同一种类型,但都可以声明数据。
  4. Integer的初始值是null,但int的初始值是0。

int和integer的一些使用:

  1. Iteger使用new去声明同样的数据,把他们进行比较得到的是false,虽然int不能用new的方式进行比较但用int方法声明的变量进行比较得到是true。(因为通过new方法生成了两个对象他们的地址是不相同的)
public static void main(String[] args) {
    int a=9;
    int b=9;
    System.out.println(a==b);//true
    Integer aa=new Integer(9);
    Integer bb=new Integer(9);
    System.out.println(aa==bb);//false
}
  1. 如果我们将相同数据int类型的数和Integer类型的数进行比较,不管是否通过new方法,得到的结果都是true。(因为Integer在和int比较时会调用一个intValue()的方法将返回一个int类型的数)
int a=9;
Integer bb=new Integer(9);
System.out.println(a==bb);//true
  1. 对于两个非new生成的Integer对象,进行比较时,如果两个变量的值在区间-128到127之间,则比较结果为true,如果两个变量的值不在此区间,则比较结果为false。(因为在-128到127之间的数已经被提前声明,再声明直接让变量指向就可以了,而如果超过这个区间那就需要调用new方法重新声明一个)
Integer aa=new Integer(128);
Integer bb=new Integer(128);
System.out.println(aa==bb);//false

Integer的装箱和封箱

装箱
Integer b=Integer.valueOf(2);

valueOf源码

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

IntegerCache源码(建议新手不要看,因为你看了也看不懂)

private static class IntegerCache {
    static final int low = -128;
    static final int high;
    static final Integer cache[];

    static {
        // high value may be configured by property
        int h = 127;
        String integerCacheHighPropValue =
            sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
        if (integerCacheHighPropValue != null) {
            try {
                int i = parseInt(integerCacheHighPropValue);
                i = Math.max(i, 127);
                // Maximum array size is Integer.MAX_VALUE
                h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
            } catch( NumberFormatException nfe) {
                // If the property cannot be parsed into an int, ignore it.
            }
        }
        high = h;

        cache = new Integer[(high - low) + 1];
        int j = low;
        for(int k = 0; k < cache.length; k++)
            cache[k] = new Integer(j++);

        // range [-128, 127] must be interned (JLS7 5.1.7)
        assert IntegerCache.high >= 127;
    }

    private IntegerCache() {}
}

装箱也就是把一个int类型的数通过封装变成一个Integer类型的数据。

封箱
System.out.println(b.intValue());

intValue源码

public int intValue() {
    return value;
}

封箱就是把Integer类型的数变成int类型的数据。
[1]https://blog.csdn.net/babycan5/article/details/81942230
[2]https://www.cnblogs.com/guodongdidi/p/6953217.html
[3]https://blog.csdn.net/sunhuaqiang1/article/details/51958714

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值