int与Integer几个例子

本文详细解析了Java中自动装箱与拆箱的机制,包括基本数据类型与包装类之间的转换过程,以及IntegerCache的工作原理,揭示了在特定范围内的Integer对象是如何复用的。

1、自动的装箱与拆箱机制:
Java为每个基本的数据类型提供类包装类,对应关系如下:
在这里插入图片描述
从java5引入了自动的拆箱与装箱的机制,使基本的数据类型与包装类能相互转换;

public class AutoUnboxingTest {
  public static void main(String[] args) {
	Integer a=new Integer(3);
	Integer b=3;
	int c=3;
	System.out.println("a==b:"+(a==b));//两个引用类型没有引用一个对象 结果为:false
	System.out.println("a==c:"+(a==c));//自动的拆箱操作 ,转成int进行比较 结果为true
  }
}
结果:
a==b:false
a==c:true

2、IntegerCache

public class IntegerCacheTest {
  public static void main(String[] args) {
    Integer f1=100,f2=100,f3=150,f4=150;
    System.out.println(f1==f2);
    System.out.println(f3==f4);
 }
}
结果:
true
false

分析:
1、f1,f2,f30,f4都是Integer类型,都是引用类型
2、==比较的就是引用的内存地址
3、当给一个Integer赋值一个int值时,就是装箱操作时就会调用valueOf方法,看一下这个方法:

  /**
     * Returns an {@code Integer} instance representing the specified
     * {@code int} value.  If a new {@code Integer} instance is not
     * required, this method should generally be used in preference to
     * the constructor {@link #Integer(int)}, as this method is likely
     * to yield significantly better space and time performance by
     * caching frequently requested values.
     *
     * This method will always cache values in the range -128 to 127,
     * inclusive, and may cache other values outside of this range.
     *
     * @param  i an {@code int} value.
     * @return an {@code Integer} instance representing {@code i}.
     * @since  1.5
     */
    public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

IntegerCache是Integer 的内部类;
源码如下:

/**
     * Cache to support the object identity semantics of autoboxing for values between
     * -128 and 127 (inclusive) as required by JLS.
     *
     * The cache is initialized on first usage.  The size of the cache
     * may be controlled by the {@code -XX:AutoBoxCacheMax=<size>} option.
     * During VM initialization, java.lang.Integer.IntegerCache.high property
     * may be set and saved in the private system properties in the
     * sun.misc.VM class.
     */

    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() {}
    }

总结:
1、如果整数值在-128-127之间的值是不会new 新的Integer的对象的,而是直接的引用常量池中的Integer对象;

<think>嗯,用户想了解Java中intInteger的区别。首先,我需要回顾基本类型和包装类的概念。基本类型int是原始数据类型,而Integer是它的包装类。接下来,应该从内存使用、默认值、性能、自动装箱拆箱这几个方面来比较。 用户提到的引用[1]和[2]中有关于Integer比较的例子,比如使用==和equals的不同结果。这里需要解释为什么两个Integer对象用==比较会返回false,而equals则为true,同时自动装箱的情况比如Integer a = 100的情况可能涉及缓存机制,值在-128到127之间会复用对象,这时候用==比较可能得到true,但超出范围就会创建新对象,导致==结果为false。 还要提到null的处理,Integer可以为null,而int不能,否则会引发NullPointerException。引用[3]中提到的强制转换问题,可能是在使用包装类时尝试转换null导致的异常,这也是需要注意的地方。 性能方面,基本类型int存储在栈上,效率更高,而Integer作为对象存在堆中,需要额外的内存开销。自动装箱和拆箱可能会影响性能,特别是在循环或大量操作时。 应用场景的话,基本类型用于数值计算,而包装类用于泛型、集合等需要对象的地方,比如ArrayList<Integer>。另外,数据库映射时也可能用到包装类,因为字段可能为NULL。 需要确保回答结构清晰,分点列出,并引用相关的例子来说明。同时要生成相关问题,帮助用户进一步理解。比如,自动装箱拆箱的机制,如何选择使用,以及相关的性能优化等。</think>### Java中intInteger的区别 #### 1. **基本概念** - **`int`**:是Java的8种基本数据类型之一,直接存储数值,不涉及对象引用。例如:`int num = 10;` - **`Integer`**:是`int`的包装类,属于引用类型,提供对象化的操作。例如:`Integer numObj = new Integer(10);` #### 2. **内存分配** - **`int`**:存储在栈内存中,直接分配空间存储数值,内存占用固定(4字节)。 - **`Integer`**:存储在堆内存中,需要对象头和其他元数据,占用更多内存[^1]。 #### 3. **默认值** - **`int`**:默认值为`0`。 - **`Integer`**:默认值为`null`(可能导致`NullPointerException`)[^3]。 #### 4. **比较操作** - **`==``equals`的区别**: - **`int`**:只能用`==`比较数值是否相等。 - **`Integer`**: - `==`比较对象内存地址(是否指向同一对象)[^2]。 - `equals()`比较包装的数值是否相等。 示例: ```java Integer x = 100; // 自动装箱,使用缓存(-128~127) Integer y = 100; System.out.println(x == y); // true(缓存范围内) System.out.println(x.equals(y)); // true ``` #### 5. **自动装箱拆箱** - **自动装箱**:将`int`隐式转换为`Integer`(如`Integer a = 10;`)。 - **自动拆箱**:将`Integer`隐式转换为`int`(如`int b = a;`)。 - **潜在问题**:频繁装箱/拆箱可能影响性能,例如循环中大量操作时[^1]。 #### 6. **应用场景** - **`int`**:适用于数值计算、循环控制等高频操作场景。 - **`Integer`**: - 集合框架(如`List<Integer>`)。 - 数据库映射(允许`null`表示缺失值)。 - 需要对象化操作的场景(如反射、泛型)。 --- ### 选择建议 - **优先使用`int`**:在不需要对象特性或`null`值的场景下,性能更优。 - **必须使用`Integer`**:在泛型、集合或需要区分“值缺失”(`null`)时使用。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值