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部分源码解析的更多相关文章

  1. JVM源码分析之Java对象头实现

    原创申明:本文由公众号[猿灯塔]原创,转载请说明出处标注 “365篇原创计划”第十一篇. 今天呢!灯塔君跟大家讲: JVM源码分析之Java对象头实现 HotSpot虚拟机中,对象在内存中的布局分为三 ...

  2. SpringMVC源码分析6:SpringMVC的视图解析原理

    title: SpringMVC源码分析6:SpringMVC的视图解析原理 date: 2018-06-07 11:03:19 tags: - SpringMVC categories: - 后端 ...

  3. JDK源码分析 – Integer

    Integer类的申明 public final class Integer extends Number implements Comparable<Integer> { … } Int ...

  4. JDK源码分析-Integer

    Integer是平时开发中最常用的类之一,但是如果没有研究过源码很多特性和坑可能就不知道,下面深入源码来分析一下Integer的设计和实现. Integer: 继承结构: -java.lang.Obj ...

  5. [置顶] 【Android实战】----从Retrofit源码分析到Java网络编程以及HTTP权威指南想到的

    一.简介 接上一篇[Android实战]----基于Retrofit实现多图片/文件.图文上传中曾说非常想搞明白为什么Retrofit那么屌.最近也看了一些其源码分析的文章以及亲自查看了源码,发现其对 ...

  6. Dubbo源码分析之ExtensionLoader加载过程解析

    ExtensionLoader加载机制阅读: Dubbo的类加载机制是模仿jdk的spi加载机制:  Jdk的SPI扩展加载机制:约定是当服务的提供者每增加一个接口的实现类时,需要在jar包的META ...

  7. [转] jQuery源码分析-如何做jQuery源码分析

    jQuery源码分析系列(持续更新) jQuery的源码有些晦涩难懂,本文分享一些我看源码的方法,每一个模块我基本按照这样的顺序去学习. 当我读到难度的书或者源码时,会和<如何阅读一本书> ...

  8. Redis源码分析:serverCron - redis源码笔记

    [redis源码分析]http://blog.csdn.net/column/details/redis-source.html   Redis源代码重要目录 dict.c:也是很重要的两个文件,主要 ...

  9. RecyclerView 源码分析(一) —— 绘制流程解析

    概述 对于 RecyclerView 是那么熟悉又那么陌生.熟悉是因为作为一名 Android 开发者,RecyclerView 是经常会在项目里面用到的,陌生是因为只是知道怎么用,但是却不知道 Re ...

  10. 序列化器中钩子函数源码分析、many关键字源码分析

    局部钩子和全局钩子源码分析(2星) # 入口是 ser.is_valid(),是BaseSerializer的方法 # 最核心的代码 self._validated_data = self.run_v ...

随机推荐

  1. 关于H5 移动端css 文本超出时省略号 失效的问题

    之前写代码的时候遇到一个问题,就是用了下面这段css代码来让文字超出范围隐藏并显示省略号. overflow: hidden; text-overflow: ellipsis; display: -w ...

  2. Java中的IO流(三)

    上一篇<Java中的IO流(二)>把学习Java的字符流以及转换流作了一下记录,从本篇开始将把IO流中对文件或文件夹操作的对象File类的学习进行一下记录. 一,File类的构造函数及字段 ...

  3. oracle表空间的创建+权限分配

    /*分为四步 */ /*第1步:创建临时表空间 */ create temporary tablespace user_temp tempfile 'D:\oracle\oradata\Oracle9 ...

  4. Swift_方法

    Swift_方法 点击查看源码 ///方法 class Methods: NSObject { func test() { // self.testInstanceMethods() //实例方法 s ...

  5. WebPack系列之Proxy

    背景 当我们直接去访问https://m.weibo.cn/api/config/list时由于端口.域名的不同产生了跨域,无法请求到资源数据. 分析 WebPack中devServer的proxy代 ...

  6. linux 第十天学习

    一.RAID 1.常见RAID (RAID 0.RAID1.RAID5.RAID10) 2.RAID 10 阵列添加 2.1.添加硬盘 2.2.查看系统加载 2.3.mdadm 命令添加RAID阵列 ...

  7. Eclipse报The default workspace'xxxxx' is in use or cannot be created Pl

    原因:出现这种情况一般是workspace的配置文件中出现了.lock文件(workspace/.metadata/.lock),锁定了workspace.把.lock文件删除即可.如果该文件不能删除 ...

  8. python中mysql主从同步配置的方法

    1)安装mysql ubuntu中安装一台mysql了,docker安装另外一台mysql 获取mysql的镜像,主从同步尽量保证多台mysql的版本相同,我的ubuntu中存在的mysql是5.7. ...

  9. 最新Altium_Designer_Beta_18.7.is AD18安装教程及破解说明

    下解Altium_Designer带破解的压缩包. 下载链接:https://pan.baidu.com/s/1TlPHtSthJKxLcXWcCR-q-g 密码:bt0g 解压缩Altium_Des ...

  10. 检测微信小程序是否被反编译获取源码

    众所周知,微信小程序的代码安全性很弱,很容易被别人反编译获取源码.我自己的小程序也被别人反编译拿到源码还上线了,非常无语. 既然客户端不好防范,服务端还是可以做点手脚的. 小程序的Referer是不可 ...