Java包装类中valueOf() 方法

valueOf() 方法的作用?

官方文档里对valueOf()方法的定义如下:

Returns an Integer instance representing the specified int value. If a new Integer instance is not required, this method should generally be used in preference to the constructor 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.

Integer (Java Platform SE 8 ) (oracle.com) )

整理可得:
  1. 该方法会返回表示指定int值的缓存池中的对象,多次调用会取得同一个对象的引用。这有助于多次使用相同同一个值时减少内存消耗。
  2. 此方法将始终缓存固定范围内的值,**并且可能缓存此范围之外的其他值。**可以自行设置。
Java 8 中Integr包装类该方法源码如下:
public static Integer valueOf(int i) {
    if (i >= IntegerCache.low && i <= IntegerCache.high)
        return IntegerCache.cache[i + (-IntegerCache.low)];
    return new Integer(i);
}

分析源码可以知道,valueOf()使用时:

  • 要调用值在缓冲池中:返回返回值中内容。
  • 不在缓冲池范围内:新建对应包装类类型对象。
由其方法特性延伸的注意点:
  1. 所谓128陷阱,现象上看是因为:IntegerCache中内设的缓冲池值区间为**-128~127。

    实际是编译器会在缓冲池范围内的基本类型自动装箱过程调用 valueOf() 方法,因此多个 实例使用自动装箱来创建并且值相同,那么就会引用相同的对象。

    		Integer aa=-128;
            Integer a=-128;
            System.out.println(a==aa);//true
    
    		Integer b1=127;
            Integer b2=Integer.valueOf(127);
            System.out.println(b1==b2);//true
    
  2. 而不在缓冲池范围内的值则无该特性,两者指向不同的引用地址,此时使用"=="比较的是两对象的地址是否相同,而应该使用equals()方法来比较包装类的值是否相同

		Integer a1=128;
        Integer a2=Integer.valueOf(128);
 		System.out.println(a1==a2);//false
		
		System.out.println(a1.equals(a2));//true
  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值