1、 public final class Integer extends Number implements Comparable<Integer>
2、toString( )方法先得到参数i的长度,然后以该长度生成char类型的buf数组,最后以该buf数组作为参数调用new String(buf, true)生成一个String对象。必须先判断Integer.MIN_VALUE,因为getChars()方法中使用了i=-i,以负数为基准,对于i=Integer.MIN_VALUE将会产生溢出。
public static String toString(int i) {
if (i == Integer.MIN_VALUE)
return "-2147483648";
int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i);
char[] buf = new char[size];
getChars(i, size, buf);
return new String(buf, true);
}
3、调用Integer.valueOf( )方法时先判断给定的数是否在-128~127之间(其中-128写死,而127值可以设置),若在该范围内,直接返回Cache数组中的Integer对象(见5),否则生成一个Integer对象。
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
4、覆盖了Object类中的hashcode函数,Integer内部定义了final类型的int变量保存该Integer的值,该Integer对象的hashcode即是其value值。
private final int value;
public Integer(int value) {
this.value = value;
}
@Override
public int hashCode() {
return Integer.hashCode(value);
}
public static int hashCode(int value) {
return value;
}
public boolean equals(Object obj) {
if (obj instanceof Integer) {
return value == ((Integer)obj).intValue();
}
return false;
}
5、 Integer内部定义了一个私有的静态内部类IntegerCache,内部定义了一个Integer类型的cache数组,若给定的数在low和high之间,直接返回该数组中的Integer对象。
private static class IntegerCache {
static final int low = -128;
static final int high;
static final Integer cache[];
static {
// high value may be configured by property
int h = 127;
String integerCacheHighPropValue =
sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
if (integerCacheHighPropValue != null) {
try {
int i = parseInt(integerCacheHighPropValue);
i = Math.max(i, 127);
// Maximum array size is Integer.MAX_VALUE
h = Math.min(i, Integer.MAX_VALUE-(-low) -1);
} catch( NumberFormatException nfe) {
}
}
high = h;
cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
assert IntegerCache.high >= 127;
}
private IntegerCache() {}
}
6、@Native public static final int MIN_VALUE = 0x80000000;
@Native public static final int MAX_VALUE = 0x7fffffff;
Int类型的数值范围为 ,即-2147483648~2147483647,将0x80000000转换成二进制即为10000000 0000000 00000000 00000000,最高位代表符号位。单字节有符号整数可以存储的范围是-128~127,正数二进制表示范围0000 0000~0111 1111,即1~127,负数二进制表示范围1000 0001 ~1111 1111,即-1~-127,还有个0分别为+0和-0, 0000 0000表示+0,1000 0000表示-128,同理可得10000000 0000000 00000000 00000000表示-2147483648。
还没有评论,来说两句吧...