JDK源码分析:Integer.java部分源码解析
1)声明部:
public final class Integer extends Number implements Comparable<Integer>
extends Number, 重写方法:
public byte byteValue() {
    return (byte)value;
}
public short shortValue() {
    return (short)value;
}
public int intValue() {
    return value;
}
public long longValue() {
    return (long)value;
}
public float floatValue() {
    return (float)value;
}
public double doubleValue() {
    return (double)value;
}
implements Comparable<T>,接口实现如下:
public int compareTo(Integer anotherInteger) {
    return compare(this.value, anotherInteger.value);
}
public static int compare(int x, int y) {
    return (x < y) ? -1 : ((x == y) ? 0 : 1);
}
与实现该接口无关观察compareUnsigned方法:
compareUnsigned 例子:
Integer a1 = 0b00000000000000000000000000000001;
Integer a2 = 0b00000000000000000000000000000011;
Integer a3 = 0b10000000000000000000000000000001;
Integer a4 = 0b10000000000000000000000000000011;
int r1 = Integer.compareUnsigned(a1.intValue(),a2.intValue());
int r2 = Integer.compareUnsigned(a1.intValue(),a3.intValue());
int r3 = Integer.compareUnsigned(a3.intValue(),a4.intValue());
Out.println("a1,a2,a3,a4分别为:" + a1 +"," + a2 + "," + a3 + "," + a4);
Out.println("r1,r2,r3分别为:" + r1 +"," + r2 + "," + r3);
result:
a1,a2,a3,a4分别为:1,3,-2147483647,-2147483645
r1,r2,r3分别为:-1,-1,-1
  算法分析:比较是无符号比较方法,而默认是有符号整型,所以需要特殊方法处理。先看Integer的范围:
	  0B10000000000000000000000000000000
	  0B10000000000000000000000000000001
	  ..
	  0B11111111111111111111111111111111
	  ...
	  0B00000000000000000000000000000000
	  0B00000000000000000000000000000001
	  0B00000000000000000000000000000010
	  ...
	  0B01111111111111111111111111111111
  在同一个符号下:除符号位其他位的数字越大,那么该数字越大。+MIN.VALUE就是修改符号位。不影响同一个符号位下的大小比较,
	  假设a=-1,b=1按无符号考虑:a>b;
	  按有符合考虑:a<b,通过修改符号位,a+MIN.VALUE(正数)>b+MIN.VALUE(负数)
	  实现了无符号比较。
2)属性
@Native public static final int MIN_VALUE = 0x80000000;
@Native public static final int MAX_VALUE = 0x7fffffff;
/**
* The {@code Class} instance representing the primitive type {@code int}.
*/
public static final Class<Integer> TYPE = (Class<Integer>) Class.getPrimitiveClass("int");
/**
* All possible chars for representing a number as a String
*/
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'
};
//十位上的数值,可以根据36,取的十位上数为3
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',
} ;
//个位上的数值,可以根据36,取的个位上数为6
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 int [] sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999,99999999, 999999999, Integer.MAX_VALUE };
//避免除法操作,直接比较大小返回位数
static int stringSize(int x) {
for (int i=0; ; i++)
if (x <= sizeTable[i])
return i+1;
}
public Integer(int value) { this.value = value;}
@Native public static final int SIZE = 32;
public static final int BYTES = SIZE / Byte.SIZE;
3)内部私有类
private static class IntegerCache {
    static final int low = -128;
    static final int high;
    static final Integer cache[];  
    static {
        <span style="color:#ff0000;">// high value may be configured by property</span>
        int h = 127;
        String integerCacheHighPropValue =
            sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
        if (integerCacheHighPropValue != null) {
            try {
                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);
            } catch( NumberFormatException nfe) {
                // If the property cannot be parsed into an int, ignore it.
            }
        }
        high = h;  
        cache = new Integer[(high - low) + 1];
        int j = low;
        for(int k = 0; k < cache.length; k++)
            cache[k] = new Integer(j++);  
        // range [-128, 127] must be interned (JLS7 5.1.7)
        assert IntegerCache.high >= 127;
    }  
    private IntegerCache() {}
}
和Short.java和Byte.java一样,都是通过静态代码块初始化缓存对象数组,不过,IntegerCache对象的high可以通过JVM的启动参数设置,缺省为127。
4)初始化方法
构造函数:
public Integer(String s) throws NumberFormatException {
    this.value = parseInt(s, 10);
}
public Integer(int value) {
    this.value = value;
}
其他方法:
public static int parseInt(String s, int radix);
public static int parseInt(String s) throws NumberFormatException;
public static Integer valueOf(String s, int radix) throws NumberFormatException;
public static Integer valueOf(String s) throws NumberFormatException;
public static Integer valueOf(int i);
public static int parseUnsignedInt(String s) throws NumberFormatException;
public static int parseUnsignedInt(String s, int radix);
观察“其他方法”的代码,难点主要在下面的方法:
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) {
<span style="color:#ff0000;"> // Accumulating negatively avoids surprises near MAX_VALUE
//该方法返回该字符根据进制对应的数字,比如2进制1那么返回1,比如16进制F那么返回15
digit = Character.digit(s.charAt(i++),radix);//i++:0->1
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;</span>
}
} else {
throw NumberFormatException.forInputString(s);
}
return negative ? result : -result;
}
该代码段例子分析:
F1F(16进制)
       (1)digit 15;result *= radix -》0;result -= digit -》 -15 
	                    (2)digit 1;result *= radix -》-15*16;result -= digit -》 -15*16 - 1(相当于累加) 
	                    (3)digit 15;result *= radix -》-(15*16+1)*16;result -= digit -》 -(15*16+1)*16 - 15
	                    (4)-( -(15*16+1)*16 - 15)= (15*15+1)*16 + 15
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);
}
}
例子:
Integer a11 = 3;
Integer a6 = Integer.parseInt("11",2);
Integer a7 = Integer.parseUnsignedInt("80000000",16);
Integer a9 = Integer.valueOf(3);
Integer a10 = new Integer(3);
boolean b1 = a6==a9;//true
boolean b2 = a6==a11;//true
boolean b3 = a6==a10;//false
初始化对象进行使用parseInt或者valueOf方法,如果值在IntegerCache范围内,可以直接获取对象。
5)一些toXXXString方法:
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] = '-';
    }
        //从buf数组的charPos位置开始截取33-charPos字符转换为String类型
    return new String(buf, charPos, (33 - charPos));
}
分析该函数之前,我们用十进制转换为二进制来解释下算法:比如10,10%2 商5余0;5%2 商2余1;2%2 商1余0;2%1 商0余1,把余数倒序拼接1010,1010就是二进制。i++号在后面的意思是先赋值然后自身加1;++i在前面的是先自身加1后赋值;--同样。
public static String toUnsignedString(int i, int radix);
public static String toHexString(int i);
public static String toOctalString(int i);
public static String toBinaryString(int i){
return toUnsignedString0(i, 1);
} //前面4个方法都是调用该方法,shift:次幂
private static String toUnsignedString0(int val, int shift) {
// assert shift > 0 && shift <=5 : "Illegal shift value";
//获取有效的二进制的位数 31位二进制
int mag = Integer.SIZE - Integer.numberOfLeadingZeros(val);
//一个算法,可以根据二进制的有效位数,求出8进制或者16进制的位数
//比如0100 0000 shift=3 -》 (7+(3-1))/3 = 3 八进制需要3位表示
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);
} //转换为2进制,高位-》低位,直至遇到1停止,0的个数
//比如0000 0000 0000 0000 0000 0000 0000 0001-》31
//比如0100 0000 0000 0000 0000 0000 0000 0001-》1
//比如0010 0000 0000 0000 0000 0000 0000 0001-》2
public static int numberOfLeadingZeros(int i) {
// HD, Figure 5-6
if (i == 0)
return 32;
int n = 1;
if (i >>> 16 == 0) { n += 16; i <<= 16; }
if (i >>> 24 == 0) { n += 8; i <<= 8; }
if (i >>> 28 == 0) { n += 4; i <<= 4; }
if (i >>> 30 == 0) { n += 2; i <<= 2; }
n -= i >>> 31;
return n;
} static int formatUnsignedInt(int val, int shift, char[] buf, int offset, int len) {
int charPos = len;
int radix = 1 << shift;
int mask = radix - 1;
do {
//val&mask 可以获取末尾使用该进制表示的数值
//例子 假设16进制
// 1010 1010 1010 1000
//& 0000 0000 0000 1111
// 0000 0000 0000 1000
buf[offset + --charPos] = Integer.digits[val & mask];
val >>>= shift;
} while (val != 0 && charPos > 0);
return charPos;
}
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];
     // 将Integer数读入到char[]数组
    getChars(i, size, buf);
    return new String(buf, true);
}
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
    // 处理超过2的16次方的大数
    while (i >= 65536) {
        q = i / 100;
        // really: r = i - (q * 100);
        // 假设 65536 那么等于 36,根据36取的十位数和个位数上的数值
        r = i - ((q << 6) + (q << 5) + (q << 2));
        //655
        i = q;
        //个位 6
        buf [--charPos] = DigitOnes[r];
        //十位 3
        buf [--charPos] = DigitTens[r];
    }  
    // Fall thru to fast mode for smaller numbers
    // assert(i <= 65536, i);
    // 处理<2的16次方的大数
    for (;;) {
        q = (i * 52429) >>> (16+3);//i*52429/524288 ≈0.1000003。相当于i/10
        //获取个位的数字
        r = i - ((q << 3) + (q << 1));  // r = i-(q*10) ...
        buf [--charPos] = digits [r];
        i = q;
        if (i == 0) break;
    }
    if (sign != 0) {
        buf [--charPos] = sign;
    }
}
一个例子:
for(int i = 0;i<65536;i++){
    int q = (i * 52429) >>> (16+3);//相当于q = i/10;
    int j = i/10;
    if(q != j){
        Out.println(false);
    }
}
输出:true
JDK源码分析:Integer.java部分源码解析的更多相关文章
- JVM源码分析之Java对象头实现
		原创申明:本文由公众号[猿灯塔]原创,转载请说明出处标注 “365篇原创计划”第十一篇. 今天呢!灯塔君跟大家讲: JVM源码分析之Java对象头实现 HotSpot虚拟机中,对象在内存中的布局分为三 ... 
- SpringMVC源码分析6:SpringMVC的视图解析原理
		title: SpringMVC源码分析6:SpringMVC的视图解析原理 date: 2018-06-07 11:03:19 tags: - SpringMVC categories: - 后端 ... 
- JDK源码分析 – Integer
		Integer类的申明 public final class Integer extends Number implements Comparable<Integer> { … } Int ... 
- JDK源码分析-Integer
		Integer是平时开发中最常用的类之一,但是如果没有研究过源码很多特性和坑可能就不知道,下面深入源码来分析一下Integer的设计和实现. Integer: 继承结构: -java.lang.Obj ... 
- [置顶]
        【Android实战】----从Retrofit源码分析到Java网络编程以及HTTP权威指南想到的
		一.简介 接上一篇[Android实战]----基于Retrofit实现多图片/文件.图文上传中曾说非常想搞明白为什么Retrofit那么屌.最近也看了一些其源码分析的文章以及亲自查看了源码,发现其对 ... 
- Dubbo源码分析之ExtensionLoader加载过程解析
		ExtensionLoader加载机制阅读: Dubbo的类加载机制是模仿jdk的spi加载机制: Jdk的SPI扩展加载机制:约定是当服务的提供者每增加一个接口的实现类时,需要在jar包的META ... 
- [转] jQuery源码分析-如何做jQuery源码分析
		jQuery源码分析系列(持续更新) jQuery的源码有些晦涩难懂,本文分享一些我看源码的方法,每一个模块我基本按照这样的顺序去学习. 当我读到难度的书或者源码时,会和<如何阅读一本书> ... 
- Redis源码分析:serverCron - redis源码笔记
		[redis源码分析]http://blog.csdn.net/column/details/redis-source.html Redis源代码重要目录 dict.c:也是很重要的两个文件,主要 ... 
- RecyclerView 源码分析(一) —— 绘制流程解析
		概述 对于 RecyclerView 是那么熟悉又那么陌生.熟悉是因为作为一名 Android 开发者,RecyclerView 是经常会在项目里面用到的,陌生是因为只是知道怎么用,但是却不知道 Re ... 
- 序列化器中钩子函数源码分析、many关键字源码分析
		局部钩子和全局钩子源码分析(2星) # 入口是 ser.is_valid(),是BaseSerializer的方法 # 最核心的代码 self._validated_data = self.run_v ... 
随机推荐
- @RestController失效
			@RestController 注解失效.就是本来应该是直接返回数据.而不是去查找视图.但是去查找视图了.我这人不喜欢弄一些无用的配置文件.所以用到什么.引用什么.但是也容易犯错误.不过也好.对哪里出 ... 
- Python基础知识--Slice(切片)和Comprehensions(生成式)
			最近在Youtube的Python视频教程上学习Python相关的基础知识,视频由Corey Schafer制作,讲得十分简单明了,英文发音也比较清晰,几乎都能听懂,是一个不错的Python入门学习的 ... 
- 如何利用Linux去油管下载带字幕的优质英文资料提升英文听力和词汇量
			非常方便地从油管下载你需要的任何英文视频资料,并且带字幕,方便你学习某个特定领域的词汇: [step1,Centos6系统安装youtbe-dl下载带英文字幕的视频] 1.首先需要安装youtube- ... 
- js中回调函数写法
			第一种方式 function studyEnglish(who){ document.write(who+"学习英语</br>"); } function study( ... 
- 使用js实现单向绑定
			详细解释单向绑定 参考资料 MDN addEventListener()定义与用法 <!DOCTYPE html> <html lang="en"> < ... 
- python应用:爬虫框架Scrapy系统学习第二篇——windows下安装scrapy
			windows下安装scrapy 依次执行下列操作: pip install wheel pip install lxml pip install PyOpenssl 安装Microsoft visu ... 
- JAVA基础 - 类的构造与实例化
			一个简单的demo,主要运用: 抽象类,类的继承 类的实例化,构造函数 @Override重写父类方法 package week4; abstract class Person { void show ... 
- Python(ATM机low版)
			import osclass ATM: @staticmethod def regst(): while 1: nm = input('请输入你的名字:') mm = input('请输入你的密码:' ... 
- 二维离散余弦变换(2D-DCT)
			图像处理中常用的正交变换除了傅里叶变换以外,还有一些其它常用的正交变换,其中离散余弦变换DCT就是一种,这是JPEG图像压缩算法里的核心算法,这里我们也主要讲解JPEG压缩算法里所使用8*8矩阵的二维 ... 
- categorical[np.arange(n), y] = 1  IndexError: index 2 is out of bounds for axis 1 with size 2
			我的错误的代码是:train_labels = np_utils.to_categorical(train_labels,num_classes = 3) 错误的原因: IndexError: ind ... 
