黑马程序员技术交流社区
标题:
对象包装类的新特性的一个小问题
[打印本页]
作者:
冯佩
时间:
2013-1-25 20:35
标题:
对象包装类的新特性的一个小问题
本帖最后由 张向辉 于 2013-1-26 16:53 编辑
从代码Integer.toString(35).getClass()可以得出整数35被转成的字符串值的类型,即String。而Integer.parseInt("135").getClass()则会报错,这说明"135"被转成的整数值是自动拆箱后的结果,而不是被封装的整数对象,这是java默认的情况吗?请解释一下除了new Integer("135")这样直接被封装成整数对象的情况外,还有什么时候是以对象存在的?
作者:
刘军亭
时间:
2013-1-25 20:44
Integer i = Integer.parseInt("135");//因为 Integer.parseInt("135");返回的是一个int类型的数据。int是基本类型所以调用getClass();时候会出错
i.getClass();
System.out.println(i.getClass());
这样就可以了,
作者:
黑马张英涛
时间:
2013-1-25 21:12
"135"被转成整数值没有进行拆箱操作。。。只是用了Integer类中的一个静态方法而已,是计算得出来的,源代码如下:
public static int parseInt(String s) throws NumberFormatException {
return parseInt(s,10);
}
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;
}
复制代码
作者:
胡勇敏
时间:
2013-1-25 21:33
沙发正解。
作者:
黄锦成
时间:
2013-1-25 23:08
Integer.parseInt("135")是int类型,它不会因为你调用了方法而装箱为Integer
还有 Integer i = 135;这时就是以对象存在
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2