通过Integer包装类将字符串转成int类型有三种方式:但是底层全部都调用了parseInt()方法。
字符串转int整型代码如下:
//将数值型字符串通过包装类Integer转为int整型
String n=“123”;
int num=Integer.parseInt(n);
System.out.println(“num为:”+num);
字符串转整型的三种方式如下:
parseInt内部底层实现:先比较要转的字符是否为空,然后判断进制radix是否在最小进制2到最大进制36之间,如果格式不正确返回异常(数据格式异常)NumberFormatException
String类下的charAt(index)方法
charAt方法可以定位一个String类型变量的某个索引单元的元素,括号内的参数是String类型变量的索引,charAt方法获得指定索引处的字符数据。
ParseInt()底层代码:将数值型字符串转换为整型
public static int parseInt(String s, int radix)
throws NumberFormatException
{
/*
* WARNING: This method may be invoked early during VM initialization
* before IntegerCache is initialized. Care must be taken to not use
* the valueOf method.
*/
if (s == null) {
throw new NumberFormatException("null");
}
if (radix < Character.MIN_RADIX) {
throw new NumberFormatException("radix " + radix +
" less than Character.MIN_RADIX");
}
if (radix > Character.MAX_RADIX) {
throw new NumberFormatException("radix " + radix +
" greater than Character.MAX_RADIX");
}
int result = 0;
boolean negative = false;
int i = 0, len = s.length();
int limit = -Integer.MAX_VALUE;
int multmin;
int digit;
if (len > 0) {
char firstChar = s.charAt(0);
if (firstChar < '0') { // Possible leading "+" or "-"
if (firstChar == '-') {
negative = true;
limit = Integer.MIN_VALUE;
} else if (firstChar != '+')
throw NumberFormatException.forInputString(s);
if (len == 1) // Cannot have lone "+" or "-"
throw NumberFormatException.forInputString(s);
i++;
}
multmin = limit / radix;
while (i < len) {
// Accumulating negatively avoids surprises near MAX_VALUE
digit = Character.digit(s.charAt(i++),radix);
if (digit < 0) {
throw NumberFormatException.forInputString(s);
}
if (result < multmin) {
throw NumberFormatException.forInputString(s);
}
result *= radix;
if (result < limit + digit) {
throw NumberFormatException.forInputString(s);
}
result -= digit;
}
} else {
throw NumberFormatException.forInputString(s);
}
return negative ? result : -result;
}
字符串转int类型底层代码实现
private static int demo5(String numStr, int radix) {
//获得字符串里面每个字符数据
Objects.requireNonNull(numStr);
//获得字符串的长度
int length = numStr.length();
if (length == 0) {
throw new NumberFormatException("字符串长度为0,无法解析!");
}
int index = 0;
int result = 0;
boolean flag = false;
//第一个字符
char firstChar = numStr.charAt(0);//获得字符串指定索引的字符数据
if (firstChar == '-') {
flag = true;
index++;
} else if (firstChar == '+') {
index++;
} else if (firstChar < 48 || firstChar > 57) {
throw new NumberFormatException("字符串里面包含非数字的数据");
}
while (index < length) {
char ch = numStr.charAt(index++);//字符数据 48-57
if (ch < 48 || ch > 57) {
throw new NumberFormatException("字符串里面包含非数字的数据");
}
int num = ch - 48;
result = result * radix + num;
}
return flag ? -result : result;
}
示例如下:
String numStr=“abcd”;
char ch = numStr.charAt(index++);
char类型转包装类型Character(装箱)
上述三种装箱方式都等同于:
装箱都是在包装类型的常量池cache中拿数据,如果数据超过常量池中的范围,则重新new出一片内存区域。代码如下: