int和Integer
基本区别
- 首先int是八大基本数据类型其中的一员,Integer是封装了方法的类
- Integer既然是类那么就必须实例化,而int是不要实例化的
- Integer默认值是null,int的默认值是0
操作实例
public static void main(String[] args) {
Integer i = new Integer(100);
int i1 = 100;
System.out.println(i==i1);//true 此处自动拆箱与int i1进行值比较
Integer i2 = new Integer(100);
Integer i3 = new Integer(100);
System.out.println(i2==i3);//false new出的新对象地址肯定是不相等的
Integer i4 = 100;
Integer i5 = 100;
System.out.println(i4==i5);//true 会翻译成为Integer i = Integer.valueOf(100),Integer会缓存-128到127之间的整数值
Integer i6 = new Integer(100);
Integer i7 = 100;
System.out.println(i6==i7);//false i7指向的是常量池中的100,而i6是重新new了一个新的对象
源码参考
public static Integer valueOf(int i) { //解释成valueOf方法
if(i >= -128 && i <= IntegerCache.high)
return IntegerCache.cache[i + 128];
else
return new Integer(i);
}
private static class IntegerCache {
static final int high;
static final Integer cache[];
static {
final int low = -128;
// high value may be configured by property
//默认最大值,可以自定义
int h = 127;
if (integerCacheHighPropValue != null) {
// Use Long.decode here to avoid invoking methods that
// require Integer's autoboxing cache to be initialized
int i = Long.decode(integerCacheHighPropValue).intValue();
i = Math.max(i, 127);
// Maximum array size is Integer.MAX_VALUE
h = Math.min(i, Integer.MAX_VALUE - -low);
}
high = h;
cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
}
private IntegerCache() {}
}
private static String integerCacheHighPropValue;//保存缓存
static void getAndRemoveCacheProperties() {
if (!sun.misc.VM.isBooted()) {
Properties props = System.getProperties();
integerCacheHighPropValue =
(String)props.remove("java.lang.Integer.IntegerCache.high");
if (integerCacheHighPropValue != null)
System.setProperties(props); // remove from system props
}
}
总结
通过源码就能够解释第三个例子为什么为true了,-128至127这个特殊区间划重点
尽可能使用包装类,其中内置方法能够在业务中便捷处理数据,不然需要多一步数据处理过程
本文详细解析了Java中int与Integer的区别,包括基本数据类型与封装类的概念、默认值的不同,以及实例化与自动装箱拆箱的过程。通过源码分析了Integer缓存机制,解释了特定情况下的对象比较结果。
188

被折叠的 条评论
为什么被折叠?



