什么是Java中的.intValue()? [英] What is .intValue() in Java?
问题描述
它们之间有什么区别?
l
是一个整数类型的arraylist。
l
is an arraylist of Integer type.
版本1:
int[] a = new int[l.size()];
for (int i = 0; i < l.size(); i++) {
a[i] = l.get(i);
}
return a;
版本2:
int[] a = new int[l.size()];
for (int i = 0; i < l.size(); i++) {
a[i] = l.get(i).intValue();
}
return a;
推荐答案
l.get(i );
将返回 Integer
然后调用 intValue();
就会返回整数类型 int
。
l.get(i);
will return Integer
and then calling intValue();
on it will return the integer as type int
.
将 int
转换为整数
被称为拳击。
将整数
转换为 int
被称为取消装箱
依此类推其他原始类型及其相应的Wrapper类之间的转换。
Converting an int
to Integer
is called boxing.
Converting an Integer
to int
is called unboxing
And so on for conversion between other primitive types and their corresponding Wrapper classes.
从java 5开始,它将自动为您执行所需的转换(自动装箱),因此如果您使用的是Java 5或更高版本,则在您的示例中没有区别即可。 如果 Integer
为null,您唯一要注意的是,并直接将其分配给 int
然后它会抛出NullPointerException。
Since java 5, it will automatically do the required conversions for you(autoboxing), so there is no difference in your examples if you are working with Java 5 or later. The only thing you have to look after is if an Integer
is null, and you directly assign it to int
then it will throw NullPointerException.
在java 5之前,程序员自己不得不做装箱/拆箱。
Prior to java 5, the programmer himself had to do boxing/unboxing.
这篇关于什么是Java中的.intValue()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!