Java中为什么要使用Integer呢?阐述Integer与int的区别

(1)设计Integer封装类型的原因是:

  Java本身就是一个面向对象的编程语言,一切操作都是以对象作为基础,如像ArrayList,HashSet,Hashtable,HashMap等集合类中存储的元素,只支持存储Object类型,又如同泛型的设计,统统表现出了Java对于封装类型的重用,而对于int,byte,short,float,char,long,double这种基本数据类型其实用的很少,且这类型的数据是无法通过集合来进行存储的。除此之外,在Java中,几乎处处都是以面向对象的思想来进行方法设计的。

(2)Integer与int的主要区别:

  ① Integer是一个引用类型,也是常说的包装类,而int是一个基本数据类型,二者可以通过装箱和拆箱来进行相互转化。

  ② Integer的初始值是null(因为它是一个实例对象),而int的初始值为0,Integer需要判空处理。

  ③ Integer是存储在堆内存中的(因为它是一个实例对象),而int类型是直接存储在栈空间的。

  ④ Integer是一个对象类型,它类的内部封装了很多的方法和属性,我们在使用的时候会更加灵活和充满选择。

  ⑤ Integer缓存机制:为了节省内存空间和提高性能,Integer类在内部通过使用相同对象引用实现缓存和重用,Integer类默认在-128~127之间,这种机制仅在自动装箱时候有用,在使用构造器创建Integer对象的时候无用。

  代码演示:

 

@Test
public void testIntegerCache(){
    Integer c = 123; // 中间值
    Integer d = 123;
    Integer x = 129; // 超出范围     Integer y = 129;     
    // 判断 -123 == -123 ? true : false
    System.out.println(c == d);
    // 判断 129 == 129 ? true : false
    System.out.println(x == y);
} 
输出:true
   false

 

对于以上出现的现象简单的解释就是,对于在规定范围内的,是可以进行缓存的,即c创建完123后,当创建d的时候发现同样也是123,且存在于cache数组中,则就不再重复创建,两个引用的地址是相同的。

而对于x和y正好相反,当创建完x后,再创建y的时候,发现这个数值并不在这个缓冲数组cache范围内,所以会重新创建新Integer对象y,故x和y是不同的,两个引用的地址是不同的。

接下来看一下这个设计原理吧

// 私有静态类IntegerCache内的部分代码块和方法        
static
final int low = -128; // Integer缓存数组的下界 static final int high;  // Integer缓存数组的上界,可以进行属性设置 static final Integer cache[]; // Integer缓存数组,是否创建一个新的Integer对象就看所创建的Integer的数值是否在这个缓冲数组的范围内了 static { // high value may be configured by property int h = 127; String integerCacheHighPropValue = sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high"); // 获取到设置的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; }
// 该方法会在创建完Integer i = value后执行,从而决定是给你缓存内的Integer对象还是新给你创建一个Integer对象
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
// 重写的equals方法和hashcode方法
public boolean equals(Object obj) {
if (obj instanceof Integer) {
return value == ((Integer)obj).intValue();
}
return false;
}
@Override
public int hashCode() {
return Integer.hashCode(value);
}

 

posted @ 2023-05-05 15:20  RS_mine  阅读(910)  评论(0)    收藏  举报