Integer类是实体类中必不可少的一个包装类型,其它类中可能也会用到,下面我来讲讲Integer类的源码分析:
/**
*@author nice
*继承了Number类实现了Comparable<Integer>接口
*/
public final class Integer extends Number implements Comparable<Integer>
{
/**
*最小值
*/
@Native public static final int MIN_VALUE = 0x80000000;
/**
*最大值
*/
@Native public static final int MAX_VALUE = 0x7fffffff;
@SuppressWarnings("unchecked")
public static final Class<Integer> TYPE = (Class<Integer>) Class.getPrimitiveClass("int");
/**
*打印成字符串
*/
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));
}
/**
*转成16进制字符串
*/
public static String toHexString(int i) {
return toUnsignedString0(i, 4);
}
/**
*转成8进制字符串
*/
public static String toOctalString(int i) {
return toUnsignedString0(i, 3);
}
/**
*转成2进制字符串
*/
public static String toBinaryString(int i) {
return toUnsignedString0(i, 1);
}
/**
*转换成对应进制的字符串
*/
private static String toUnsignedString0(int val, int shift) {
// assert shift > 0 && shift <=5 : "Illegal shift value";
int mag = Integer.SIZE - Integer.numberOfLeadingZeros(val);
int chars = Math.max(((mag + (shift - 1)) / shift), 1);
char[] buf = new char[chars];
formatUnsignedInt(val, shift, buf, 0, chars);
// Use special constructor which takes over "buf".
return new String(buf, true);
}
/**
*将int类型转换为字符串
*/
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);
}
}