栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

【Java】valueOf() 方法

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【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) )

整理可得:
    该方法会返回表示指定int值的缓存池中的对象,多次调用会取得同一个对象的引用。这有助于多次使用相同同一个值时减少内存消耗。此方法将始终缓存固定范围内的值,**并且可能缓存此范围之外的其他值。**可以自行设置。
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()使用时:

要调用值在缓冲池中:返回返回值中内容。不在缓冲池范围内:新建对应包装类类型对象。 由其方法特性延伸的注意点:

    所谓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
    

    而不在缓冲池范围内的值则无该特性,两者指向不同的引用地址,此时使用"=="比较的是两对象的地址是否相同,而应该使用equals()方法来比较包装类的值是否相同。

		Integer a1=128;
        Integer a2=Integer.valueOf(128);
 		System.out.println(a1==a2);//false
		
		System.out.println(a1.equals(a2));//true
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/715797.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号