Java_语法基础_优先使用整型池

例:

package deep;

import java.util.Scanner;

public class Client {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        while (input.hasNextInt()) {
            int ii = input.nextInt();
            System.out.println("====" + ii + "的相等判断====");
            // 两个通过new产生的Integer对象
            Integer i = new Integer(ii);
            Integer j = new Integer(ii);
            System.out.println("new产生的对象:" + (i == j));

            // 基本类型转为包装类型后比较
            i = ii;
            j = ii;
            System.out.println("基本类型转换的对象:" + (i == j));

            // 通过静态方法生成一个实例
            i = Integer.valueOf(ii);
            j = Integer.valueOf(ii);
            System.out.println("valueOf产生的对象:" + (i == j));
        }
    }
}

运行结果:
127
====127的相等判断====
new产生的对象:false
基本类型转换的对象:true
valueOf产生的对象:true
128
====128的相等判断====
new产生的对象:false
基本类型转换的对象:false
valueOf产生的对象:false
555
====555的相等判断====
new产生的对象:false
基本类型转换的对象:false
valueOf产生的对象:false

很不可思议呀,数字127的比较结果竟然与其他两个数字不同,它的装箱动作所产生的对象竟然是同一个对象,valueOf产生的也是同一个对象,但是大于127的数字128和555在比较过程中所产生的却不是同一个对象,这是为什么?我们一个一个来解释:
(1)new产生的Integer对象
new声明的就是要生成一个新的对象,没二话,这是两个对象,地址肯定不等,比较结果为false。
(2)装箱生成的对象
对于这一点,首先要说明的是装箱动作是通过valueOf方法实现的,也就是说后两个算法是相同的,那结果肯定也是一样的,现在的问题是:valueOf是如何生成对象的呢?我们来阅读以下Integer.valueOf的实现代码:

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

    /**
     * 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) {
        assert IntegerCache.high >= 127;
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

以上代码的意思已经很明了了,如果是-128到127之间的int类型转换为Integer对象,则直接从cache数组中获得,cache是IntegerCache内部类的一个静态数组,容纳的是-128到127之间的Integer对象。通过valueOf产生包装对象时,如果int参数在-128和127之间,则直接从整型池中获得对象,不在该范围的int类型则通过new生成包装对象。
明白了这一点,要理解上面的输出结果就迎刃而解了,127的包装对象是直接从整型池中获得的,不管你输入多少次127这个数字,获得的对象都是同一个,那地址当然都是相等的。而128、555超出了整型池范围,是通过new产生一个新的对象,地址不同,当然也就不相等了。
以上的解释也就是整型池的原来,整型池的存在不仅仅提高了系统性能,同时也节约了内存空间,这也是我们使用整型池的原因,也就是在声明包装对象的时候使用valueOf生成,而不是通过构造函数来生成的原因。顺便提醒大家,在判断对象是否相等的时候,最好是用equals方法,避免用“==”产生非预期结果。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值