string转int中的parseint与valueOf
首先我们先来了解什么是装箱与拆箱:
装箱:普通类型转换为包装类型
Eg:integer i=10;
拆箱:包装类转换为普通类型
Eg:int j=i;
面试与笔试中会出现的问题;
public class Main {
public static void main(String[] args) {
Integer i1 = 100; Integer i2 = 100; Integer i3 = 200; Integer i4 = 200;
System.out.println(i1==i2); System.out.println(i3==i4);
}
}
以上代码会输出什么?
结果是ture,false
为什么会这样呢?
我们知道integer对应的基础类型int的范围为[-128-127]之间,便返回指向IntegerCache.cache中已经存在的对象的引用;否则创建一个新的Integer对象。上面的代码中i1和i2的数值为100,因此会直接从cache中取已经存在的对象,所以i1和i2指向的是同一个对象,而i3和i4则是分别指向不同的对象。
下面是integer中valueof方法的具体实现:
public static Integer valueOf(int i) {
if(i >= -128 && i <= IntegerCache.high)
return IntegerCache.cache[i + 128];
else
return new Integer(i);
}
private static class IntegerCache {
static final int high;
static final Integer cache[];
static { final int low = -128;
// high value may be configured by property int h = 127; if (integerCacheHighPropValue != null) { // Use Long.decode here to avoid invoking methods that // require Integer's autoboxing cache to be initialized int i = Long.decode(integerCacheHighPropValue).intValue(); i = Math.max(i, 127); // Maximum array size is Integer.MAX_VALUE h = Math.min(i, Integer.MAX_VALUE - -low); } 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() {}
}
那如果是其他类型的呢?输出又是怎么样?主要看它的valueof的方法
注意,Integer、Short、Byte、Character、Long这几个类的valueOf方法的 实现是类似的。
Double、Float的valueOf方法的实现是类似的。
以上的内容参考于:https://www.cnblogs.com/dolphin0520/p/3780005.html
1.频繁装箱的坏处:耗时,耗能
个人觉得这个就很好理解了,通过各种调用各种出来的,一般都比较耗时,耗能。
每个人都有自己的理解方式,可以参考下面
原因:https://blog.csdn.net/u012070360/article/details/54574707
2.回归正题parseint与valueOf的区别,其实差异就在于装箱了
它们都可以实现string转int,首先我们先看一下,它们两个是如何实现的:
public static int parseInt(String s) throws NumberFormatException {
return parseInt(s,10);
}
public static Integer valueOf(String s) throws NumberFormatException {
return Integer.valueOf(parseInt(s, 10));
}
是不是看出来了首先返回的类型不一样:parseint返回的是int基础类型,valueof返回的是integer包装类型
valueOf方法实际上是调用了parseInt方法,也就是说,如果我们仅仅只需要得到字符串类型字符数值对应的整数数值,那我们大可不必调用valueOf,因为这样得到整形数值之后还要做一个装箱的操作,将int封装为Integer。
这样的一个装箱操作就导致了他们的效率问题,经过测试parse的效率更高。
参考了某博主的博客:https://www.cnblogs.com/LoganChen/p/7252419.html