有一天,突然发现,阅读原码可以发现很多有趣的东西。在Java中,我们知道很多东西都是封装好的,拿来即用,当你有一天去研究它拿来的东西是如何具体操作的,将会是非常有趣的事情。

在上一篇研究HashMap 源码的时候,发现了将任意大于某个数字的最小二次幂的实现,发现别人写的不仅漂亮而且高效。

在Java 的底层,很多高效的算法包含其中,阅读源码是非常有帮助的。

接下来将开始阅读 Integer 的源码,让自己更多的理解Integer 这个类的实现。

一.Integer 中的进制转换,包括将十进制转换为二进制及、八进制、十六进制

  1.调用方法

Integer.toBinaryString()
Integer.toOctalString()
Integer.toHexString()

 2.实现方法

 转换为二进制
public static String toBinaryString(int i) {
return toUnsignedString0(i, );
} 转换为八进制
public static String toOctalString(int i) {
return toUnsignedString0(i, );
} 转换为十六进制
public static String toHexString(int i) {
return toUnsignedString0(i, );
}

 3.底层实现

  发现所有的进制转换都是调用的 toUnsignedString0() 这个方法,其实现如下

 方法调用一
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 - )) / shift), );
char[] buf = new char[chars]; formatUnsignedInt(val, shift, buf, , chars); // Use special constructor which takes over "buf".
return new String(buf);
} 方法调用二
static int formatUnsignedInt(int val, int shift, char[] buf, int offset, int len) {
int charPos = len;
int radix = << shift;
int mask = radix - ;
do {
buf[offset + --charPos] = digits[val & mask];
val >>>= shift;
} while (val != && charPos > ); return charPos;
} 方法调用三
final static char[] digits = {
'' , '' , '' , '' , '' , '' ,
'' , '' , '' , '' , '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'
};

二. Integer 中的方法

方法1:比较2个数字的大小,若 第一个小于第二个,返回-1;若相等,返回0;若第一个大于第二个,返回1

 public static int compare(int x, int y) {
return (x < y) ? - : ((x == y) ? : );
}

方法2:  返回该数字二进制 补码中 1 的个数 

public static int bitCount(int i) {
// HD, Figure 5-2
i = i - ((i >>> ) & 0x55555555);
i = (i & 0x33333333) + ((i >>> ) & 0x33333333);
i = (i + (i >>> )) & 0x0f0f0f0f;
i = i + (i >>> );
i = i + (i >>> );
return i & 0x3f;
}

方法3: 返回String 或者 int 类型的 Integer 实例

第一步:
public static Integer valueOf(String s) throws NumberFormatException {
return Integer.valueOf(parseInt(s, ));
} 第二步:
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 = ;
boolean negative = false;
int i = , len = s.length();
int limit = -Integer.MAX_VALUE;
int multmin;
int digit; if (len > ) {
char firstChar = s.charAt();
if (firstChar < '') { // Possible leading "+" or "-"
if (firstChar == '-') {
negative = true;
limit = Integer.MIN_VALUE;
} else if (firstChar != '+')
throw NumberFormatException.forInputString(s); if (len == ) // 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 < ) {
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 Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}

方法4:将String 类型转换为 Int 类型

输入String
public static int parseInt(String s) throws NumberFormatException {
return parseInt(s,);
}   parseInt() 调用方法同上

最新文章

  1. EF循环迭代导致如此严重的性能丢失,你知道?
  2. [Java] 特殊正则-替换字符串
  3. Master page and jquery
  4. 查看oracle数据库中的保留字
  5. 【转】【JavaScript】禁用backspace键的后退功能,但是可以删除文本内容
  6. HDU 4725 The Shortest Path in Nya Graph-【SPFA最短路】
  7. JavaScript开发者必备的10个sublime的插件
  8. css雪碧图(css splite)
  9. Ansible性能调优
  10. IDEA打印gc日志,设置JVM参数方法
  11. windows Zookeeper本地服务化
  12. day70
  13. Swift编程语言学习1.7——断言
  14. 关于java泛型的使用方式。。。。
  15. Spring 开发第一步(四)Spring与JDBC事务
  16. 第六章 HashSet源码解析
  17. json.dumps 和 json.dump的区别,load和loads的区别
  18. CRC校验8
  19. 手机缺失sqlite3时操作数据库的多种解决方案 ----adb命令科普
  20. CSAcademy Palindromic Concatenation 字符串哈希

热门文章

  1. numpy+pandas 基础学习
  2. How to CORS enable ArcGIS Server 10.2.1 to Access REST Services without Using proxy.ashx
  3. django之block extend标签
  4. centos6 安装 docker 问题
  5. Swoole 内存操作(Table)
  6. curl发送xml , xml和数组互转
  7. 机器学习进阶-疲劳检测(眨眼检测) 1.dist.eculidean(计算两个点的欧式距离) 2.dlib.get_frontal_face_detector(脸部位置检测器) 3.dlib.shape_predictor(脸部特征位置检测器) 4.Orderdict(构造有序的字典)
  8. sizeof 空类
  9. jquery循环方法
  10. HTML Tags