这篇文章继续java.lang包下的源码学习,笔者也是找了几个比较常用的来阅读。下面针对Integer、Long、Double这样的基本类型的封装类,记录一些比较经典、常用的方法的学习心得,如toString()、parseInt()等。
java.lang.Integer
1. public static String toString(int i)
说起toString(),这是从Object类中继承过来的,当然,如果我们不重写,那么返回的值为ClassName + "@" + hashCode的16进制。那么,如果是我们自己,要怎么实现呢。笔者这里想到的办法是循环对10求余,得到对应的char型数组后就得到了字符串。那么我们来看看JDK中高手是怎么写的,以下是10进制的【10进制的与其它的是不一样的】。
1 public static String toString(int i) { 2 if (i == Integer.MIN_VALUE) 3 return "-2147483648"; 4 int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i); 5 char[] buf = new char[size]; 6 getChars(i, size, buf); 7 return new String(0, size, buf); 8 }
1 static void getChars(int i, int index, char[] buf) { 2 int q, r; 3 int charPos = index; 4 char sign = 0; 5 6 if (i < 0) { 7 sign = '-'; 8 i = -i; 9 } 10 11 // Generate two digits per iteration 12 while (i >= 65536) { 13 q = i / 100; 14 // really: r = i - (q * 100); 15 r = i - ((q << 6) + (q << 5) + (q << 2)); 16 i = q; 17 buf [--charPos] = DigitOnes[r]; 18 buf [--charPos] = DigitTens[r]; 19 } 20 21 // Fall thru to fast mode for smaller numbers 22 // assert(i <= 65536, i); 23 for (;;) { 24 q = (i * 52429) >>> (16+3); 25 r = i - ((q << 3) + (q << 1)); // r = i-(q*10) ... 26 buf [--charPos] = digits [r]; 27 i = q; 28 if (i == 0) break; 29 } 30 if (sign != 0) { 31 buf [--charPos] = sign; 32 } 33 }
//笔者注:取出十位数的数字。 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', }; 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' };