Java中Integer为32位,所以它的最大值最小值又如下:
/**
* A constant holding the minimum value an <code>int</code> can
* have, -2<sup>31</sup>.
*/
public static final int MIN_VALUE = 0x80000000;
/**
* A constant holding the maximum value an <code>int</code> can
* have, 2<sup>31</sup>-1.
*/
public static final int MAX_VALUE = 0x7fffffff;
Integer中使用final value保存整数值,所以与String一样Integer的内容也是不可变的
/**
* The value of the <code>Integer</code>.
*
* @serial
*/
private final int value;
一、源码方法
1、Integer.valueof(444);源码中使用内部类IntegerCache缓存了-128到127的数字,所以多次valueOf(3)会得到同一个对象,而多次valueOf(333)则是不同的对象
public static Integer valueOf(int i) {
final int offset = 128;
if (i >= -128 && i <= 127) { // must cache
return IntegerCache.cache[i + offset];
}
return new Integer(i);
}
private static class IntegerCache {
private IntegerCache(){}
static final Integer cache[] = new Integer[-(-128) + 127 + 1];
static {
for(int i = 0; i < cache.length; i++)
cache[i] = new Integer(i - 128);
}
}
2、Integer.valueOf(String "122")与Integer.parseInt(String "111")
首先前者返回的是一个Integer对象,而后置返回一个int值,源码比较发现,他们都调用了Integer.parseInt(s, radix)方法,将数字字符串转化成radix进制数
public static int parseInt(String s) throws NumberFormatException {
return parseInt(s,10);
}
public static Integer valueOf(String s) throws NumberFormatException
{
return new Integer(parseInt(s, 10));
}
3、hashCode(),返回对象的value
public int hashCode() {
return value;
}
4、intValue()返回对象的value,通常用于Integer的拆箱
public int intValue() {
return value;
}
二、装箱拆箱,是编译器进行的优化
1、自动装箱,.java文件中的代码如下:
Integer c = 3;
Integer d = 3;
Integer e = 321;
Integer f = 321;
编译完成,class文件中的代码如下:
Integer c = Integer.valueOf(3);
Integer d = Integer.valueOf(3);
Integer e = Integer.valueOf(321);
Integer f = Integer.valueOf(321);
由valueOf(int i)这个函数的源码可知,c和d指向的是同一个对象,而e和f指向的是不同的对象
2、自动拆箱,.java文件中代码如下:
int idd = c + d;
d = c + d;
编译完成,class文件中的代码如下:
int idd = c.intValue() + d.intValue();
d = Integer.valueOf(c.intValue() + d.intValue());