其他 源码解析 https://blog.csdn.net/qq_32726809/article/category/8035214
1类的声明
public final class Integer extends Number implements Comparable<Integer>
- 继承 Number
- 实现 Comparable<Integer> 可以比较大小
2类属性
@Native public static final int MIN_VALUE = 0x80000000;
@Native public static final int MAX_VALUE = 0x7fffffff;
@Native public static final int SIZE = 32;
public static final int BYTES = SIZE / Byte.SIZE;
3构造函数
public Integer(int value) {
this.value = value;
}
public Integer(String s) throws NumberFormatException {
this.value = parseInt(s, 10);
}
下面会对 parseInt(s, 10);进行详细说明
4方法
4.1toString(int i, int radix)
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) {/*--------1*/
return toString(i);
}
char buf[] = new char[33];/*--------2*/
boolean negative = (i < 0);
int charPos = 32;
if (!negative) {
i = -i;
}
while (i <= -radix) {/*--------3*/
buf[charPos--] = digits[-(i % radix)];
i = i / radix;
}
buf[charPos] = digits[-i];
if (negative) {/*--------4*/
buf[--charPos] = '-';
}
return new String(buf, charPos, (33 - charPos));
}
- 1处的意思是如果是十进制就直接返回字符串
- 2处33字符数组是因为 进制最小是2进制,而整型的2进制是32位,再加上1一个符号位,所以就33个字符。
- 3处 进行进制处理
- 4 添加符号
4.2toUnsignedString
获取整型的补码以 radix显示
public static String toUnsignedString(int i, int radix) {
return Long.toUnsignedString(toUnsignedLong(i), radix);
}
补码标注
- 正数的补码还是原码
- 负数的补码是原码取反加1。
4.3 进制转化
public static String toHexString(int i) {
return toUnsignedString0(i, 4);
}
public static String toOctalString(int i) {
return toUnsignedString0(i, 3);
}
public static String toBinaryString(int i) {
return toUnsignedString0(i, 1);/*-----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]; /*-----2*/
formatUnsignedInt(val, shift, buf, 0, chars);/*-----3*/
// Use special constructor which takes over "buf".
return new String(buf, true);
}
static int formatUnsignedInt(int val, int shift, char[] buf, int offset, int len) {
int charPos = len;
int radix = 1 << shift;/*-----4*/
int mask = radix - 1;
do {
buf[offset + --charPos] = Integer.digits[val & mask];/*-----5*/
val >>>= shift;/*-----6*/
} while (val != 0 && charPos > 0);
return charPos;
}
通过原码可以看出,转化进制调用的是同一个方法,只是参数不一样
- 1调用相同方法
- 2通过上面代码操作,可以获得最后转化为进制补码的字符串长度,从而减少不必要的内存消耗
- 3 调用求补码的方法,参数
- val 原值
- shift 1代表2进制,2代表4进制,3代表8进制,4代表16进制
- buf 代表转化完的进制字符串存储处。
- offset 开始位置
- len 长度
- 4 将传的 1,2,3,4 转化为进制数 2,4,8,16
- 5 将值与进制数进行与运算,类似于 取余操作,例如 例如20的2进制表示为 10100,10100&1111 =100 这就会获得最后四位的2进制码。
- 6进行移位,把刚才处理过的位去掉。10100移位就是 1,然后再重复5操作,便会得到 14,而20的16进制就是14。 通俗解释
就是每 shift位数转化为进制数,也就是上问中的 1,2,3,4
4.4 toString(int i)
这个方法本来不想写的,但看了源码,发现很多疑惑,分享一下
final static char[] digits = {
'0' , '1' , '2' , '3' , '4' , '5' ,
'6' , '7' , '8' , '9' , 'a' , 'b' ,
'c' , 'd' , 'e' , 'f' , 'g' , 'h' ,
'i' , 'j' , 'k' , 'l' , 'm' , 'n' ,
'o' , 'p' , 'q' , 'r' , 's' , 't' ,
'u' , 'v' , 'w' , 'x' , 'y' , 'z'
};
final static char [] DigitTens = {
'0', '0', '0', '0', '0', '0', '0', '0', '0', '0',
'1', '1', '1', '1', '1', '1', '1', '1', '1', '1',
'2', '2', '2', '2', '2', '2', '2', '2', '2', '2',
'3', '3', '3', '3', '3', '3', '3', '3', '3', '3',
'4', '4', '4', '4', '4', '4', '4', '4', '4', '4',
'5', '5', '5', '5', '5', '5', '5', '5', '5', '5',
'6', '6', '6', '6', '6', '6', '6', '6', '6', '6',
'7', '7', '7', '7', '7', '7', '7', '7', '7', '7',
'8', '8', '8', '8', '8', '8', '8', '8', '8', '8',
'9', '9', '9', '9', '9', '9', '9', '9', '9', '9',
} ;
final static char [] DigitOnes = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
} ;
public static String toString(int i) {
if (i == Integer.MIN_VALUE)
return "-2147483648";
int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i);/*-----1*/
char[] buf = new char[size];
getChars(i, size, buf);
return new String(buf);
}
static void getChars(int i, int index, char[] buf) {
int q, r;
int charPos = index;
char sign = 0;
if (i < 0) {
sign = '-';
i = -i;
}
// Generate two digits per iteration
while (i >= 65536) {
q = i / 100;
// really: r = i - (q * 100);
r = i - ((q << 6) + (q << 5) + (q << 2));
i = q;
buf [--charPos] = DigitOnes[r];
buf [--charPos] = DigitTens[r];
}
// Fall thru to fast mode for smaller numbers
// assert(i <= 65536, i);
for (;;) {
q = (i * 52429) >>> (16+3);/*-----2*/
r = i - ((q << 3) + (q << 1)); // r = i-(q*10) .../*-----3*/
buf [--charPos] = digits [r]; /*-----4*/
i = q;
if (i == 0) break;
}
if (sign != 0) {
buf [--charPos] = sign;
}
}
final static int [] sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999,
99999999, 999999999, Integer.MAX_VALUE };
// Requires positive x
static int stringSize(int x) {
for (int i=0; ; i++)
if (x <= sizeTable[i])
return i+1;
}
- 想不到吧,tostring方法竟然这么麻烦,我的疑惑是,上面既然已经有toString(int i,int j)的方法,为什么不直接调用,为什么tostring不直接 return ""+i; 呢
- 具体解释如下
- 1 处的意思是 获取 数的位数,如,12 的位数是2,2343的位数是4,查看stringSize可知,是通过调用静态数组列表来获取的。
- 2 处的意思是 个人理解,就是获取最低位前所有位的数,例如,123获取的就是12,1245获取的就是124
- 3处的意思是 就是获取最末位的数字
- 4 处的意思是根据数字大小来获取字符串中位置的值,并插入到char数组中
4.5parseInt
public static int parseInt(String s, int radix)
throws NumberFormatException
{
/*
* WARNING: This method may be invoked early during VM initialization
* before IntegerCache is initialized. Care must be taken to not use
* the valueOf method.
*/
if (s == null) {
throw new NumberFormatException("null");
}
if (radix < Character.MIN_RADIX) {
throw new NumberFormatException("radix " + radix +
" less than Character.MIN_RADIX");
}
if (radix > Character.MAX_RADIX) {
throw new NumberFormatException("radix " + radix +
" greater than Character.MAX_RADIX");
}
int result = 0;
boolean negative = false;
int i = 0, len = s.length();
int limit = -Integer.MAX_VALUE;
int multmin;
int digit;
if (len > 0) {
char firstChar = s.charAt(0);
if (firstChar < '0') { // Possible leading "+" or "-"
if (firstChar == '-') {
negative = true;
limit = Integer.MIN_VALUE;
} else if (firstChar != '+')
throw NumberFormatException.forInputString(s);
if (len == 1) // Cannot have lone "+" or "-"
throw NumberFormatException.forInputString(s);
i++;
}
multmin = limit / radix;
while (i < len) {
// Accumulating negatively avoids surprises near MAX_VALUE
digit = Character.digit(s.charAt(i++),radix);
if (digit < 0) {
throw NumberFormatException.forInputString(s);
}
if (result < multmin) {
throw NumberFormatException.forInputString(s);
}
result *= radix;
if (result < limit + digit) {
throw NumberFormatException.forInputString(s);
}
result -= digit;
}
} else {
throw NumberFormatException.forInputString(s);
}
return negative ? result : -result;
}
public static int parseInt(String s) throws NumberFormatException {
return parseInt(s,10);
}
- 其实就是把字符串拆解,然后每个char 都进行 Character.digit(s.charAt(i++),radix);解析,然后再拼接成整型
- 这里有一个问题 ,按理说 parseInt(String s,int i),i应该表示的是进制,但是,心在只有输入10是对的,其他值都会异常
4.6parseUnsignedInt(String s, int radix)
public static int parseUnsignedInt(String s, int radix)
throws NumberFormatException {
if (s == null) {
throw new NumberFormatException("null");
}
int len = s.length();
if (len > 0) {
char firstChar = s.charAt(0);
if (firstChar == '-') {
throw new
NumberFormatException(String.format("Illegal leading minus sign " +
"on unsigned string %s.", s));
} else {
if (len <= 5 || // Integer.MAX_VALUE in Character.MAX_RADIX is 6 digits
(radix == 10 && len <= 9) ) { // Integer.MAX_VALUE in base 10 is 10 digits
return parseInt(s, radix);
} else {
long ell = Long.parseLong(s, radix);
if ((ell & 0xffff_ffff_0000_0000L) == 0) {
return (int) ell;
} else {
throw new
NumberFormatException(String.format("String value %s exceeds " +
"range of unsigned int.", s));
}
}
}
} else {
throw NumberFormatException.forInputString(s);
}
}
4.7decode(String nm)
public static Integer decode(String nm) throws NumberFormatException {
int radix = 10;
int index = 0;
boolean negative = false;
Integer result;
if (nm.length() == 0)
throw new NumberFormatException("Zero length string");
char firstChar = nm.charAt(0);
// Handle sign, if present
if (firstChar == '-') {
negative = true;
index++;
} else if (firstChar == '+')
index++;
// Handle radix specifier, if present
if (nm.startsWith("0x", index) || nm.startsWith("0X", index)) {
index += 2;
radix = 16;
} else if (nm.startsWith("#", index)) {
index++;
radix = 16;
} else if (nm.startsWith("0", index) && nm.length() > 1 + index) {
index++;
radix = 8;
}
if (nm.startsWith("-", index) || nm.startsWith("+", index))
throw new NumberFormatException("Sign character in wrong position");
try {
result = Integer.valueOf(nm.substring(index), radix);
result = negative ? Integer.valueOf(-result.intValue()) : result;
} catch (NumberFormatException e) {
// If number is Integer.MIN_VALUE, we'll end up here. The next line
// handles this case, and causes any genuine format error to be
// rethrown.
String constant = negative ? ("-" + nm.substring(index)) : nm.substring(index);
result = Integer.valueOf(constant, radix);
}
return result;
}
public static Integer valueOf(String s, int radix) throws NumberFormatException {
return Integer.valueOf(parseInt(s,radix));
}
这里没有特别的逻辑,最后调的是 valueOf(constant, radix);进行转化的,而valueOf又是调用 parseInt(s,radix)转化的。