1、首先Integer提供了两类工具类,包括把一个int类型转成二进等,

Integer类源码浅析-LMLPHP

其实执行转换算法只有一个方法:

     public static String toString(int i, int radix) {

         if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
radix = 10; /* Use the faster version */
if (radix == 10) {
return toString(i);
} char buf[] = new char[33];
boolean negative = (i < 0);
int charPos = 32; if (!negative) {
i = -i;
} while (i <= -radix) {
buf[charPos--] = digits[-(i % radix)];
i = i / radix;
}
buf[charPos] = digits[-i]; if (negative) {
buf[--charPos] = '-';
} return new String(buf, charPos, (33 - charPos));
}

2、测试的示例代码

 //定义一个Integer 变量
Integer i = 1;
Integer j = 1;
System.out.println(i==j); //true Integer x = 128;
Integer y = 128;
System.out.println(x==y); //false

为什么会出现这样的结果呢,因为Integer内部维护了一个缓存类IntegerCache,默认缓存-128~127的数据

 /**
* Cache to support the object identity semantics of autoboxing for values between
* -128 and 127 (inclusive) as required by JLS.
*
* The cache is initialized on first usage. The size of the cache
* may be controlled by the -XX:AutoBoxCacheMax=<size> option.
* During VM initialization, java.lang.Integer.IntegerCache.high property
* may be set and saved in the private system properties in the
* sun.misc.VM class.
*/

IntegerCache缓存类的大小是可以设置,通过 -XX:AutoBoxCacheMax=<size> 这个选项来设置

     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) {
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);
}
high = h; cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
} private IntegerCache() {}
}

3、Integer类的内部维护了一个int基本类型的变量

提供了两个构造方法来初始化,一个构造方法接受int类型,一个接受String类型,接受类型的构造方法,调用了静态方法parseInt(s,10);

4、还有JDK1.7新添加的一个方法

     /**
* Compares two {@code int} values numerically.
* The value returned is identical to what would be returned by:
* <pre>
* Integer.valueOf(x).compareTo(Integer.valueOf(y))
* </pre>
*
* @param x the first {@code int} to compare
* @param y the second {@code int} to compare
* @return the value {@code 0} if {@code x == y};
* a value less than {@code 0} if {@code x < y}; and
* a value greater than {@code 0} if {@code x > y}
* @since 1.7
*/
public static int compare(int x, int y) {
return (x < y) ? -1 : ((x == y) ? 0 : 1);
}

其他方法就不做分析,可以直接参看API

05-16 10:21