参考文章: Java中的int与String互相转换方式_迟走的蜗牛的博客-优快云博客_javaint转string
一、String 转 int 如"123" → 123
1. Integer.parseInt(str)
2. Integer.valueOf(str).intValue()
背景知识:
1. Integer.parseInt()
static int parseInt(String s): 将字符串转为int型整数
static int parseInt(String s,int radix):将字符串按照指定进制,转为int型整数(默认10进制)
2. Integer.valueOf()
参考文章: Integer. valueOf()的使用_汪先生的博客-优快云博客_integer.valueof()作用
Integer.valueOf()方法用于返回给定参数的原生数值的对象值
Integer.valueOf(int i): 基本类型int转换为包装类型Integer
Integer.valueOf(String s): String类型转换为包装类型Integer, String为Null或""都会报错
Integer.valueOf(String s,int radix): String类型转换为指定进制的包装类型Integer
2. 1 Integer.valueOf()的高效性体现在哪?
根据Integer.valueOf()的源码:
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
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() {}
}
int在[-128,127]之间时,直接返回缓存;在这一范围之外,才会new Integer();
简言之: Integer.valueOf()方法基于减少对象创建次数和节省内存的考虑,缓存了[-128,127]之间的数字。此数字范围内传参则直接返回缓存中的对象。在此范围之外,返回new的对象
3. Integer.parseInt() 与Integer.valueOf()的区别?
参考文章:Integer.parseInt()和Integer.valueOf()有什么区别 - 为努力骄傲 - 博客园
Integer.parseInt(String str), 将数字的字符串转成数字,返回int型变量,不具备方法和属性;
Integer.valueOf(String str), 将数字的字符串转成Integer类型,相等于转成int型的包装类,具备方法和属性;
4. intValue() 方法
访问方式: 对象名.intValue()
用于返回此对象表示的值,该值通过强制类型转换为int类型,可能会涉及舍入或截断
二、int 转 String 如: 123 → "123"
1. num + "" (耗时长)
2. String.valueOf(num)
String valueOf(object)源码:
public static String valueOf(Object obj){return (obj==null)?"null":obj.toString();}
注意: 当object为null时,该方法返回"null";
3. Integer.toString(num)