0%

Integer

例子

1
2
3
4
5
6
7
Integer i1 = 33; // 装箱,会调用valueOf方法
Integer i2 = 33;
System.out.println(i1 == i2); // true

Integer i3 = 129;
Integer i4 = 129;
System.out.println(i3 == i4); // false

Integer i1 = 33 进行了装箱,因为值在 IntegerCache.low 和 IntegerCache.high 之间,直接使用的是缓存机制里常量池的值 IntegerCache.cache[i + (-IntegerCache.low)]

源码

1
2
3
4
5
6
7
8
9
10
11
12
13
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
private static class IntegerCache {
static final int low = -128;
static final int high;
static {
// high value may be configured by property
int h = 127;
}
}

非常用方法

1
2
3
4
5
6
7
8
9
10
11
12
// 16进制转10进制
public static int parseInt(String s, int radix)
throws NumberFormatException

// 进制转换方法
int n = 18;
Integer.toHexString(n);
System.out.println(n + "的二进制是:" + Integer.toBinaryString(n));
System.out.println(n + "的八进制是:" + Integer.toOctalString(n));
System.out.println(n + "的十六进制是:" + Integer.toHexString(n));
System.out.println(n + "的三进制是:" + Integer.toString(n, 3));