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. 分别利用(代码,Xib,SB)创建空的App工程

    1. 利用代码: 2.利用XIB: 3.利用Storyboard: Xcode 7默认该方式创建项目工程,就不必多说了!

  2. java ssm 后台框架平台 项目源码 websocket IM quartz springmvc

    A代码编辑器,在线模版编辑,仿开发工具编辑器,pdf在线预览,文件转换编码B 集成代码生成器 [正反双向](单表.主表.明细表.树形表,快速开发利器)+快速表单构建器freemaker模版技术 ,0个 ...

  3. iOS之iOS中的(null)、<null>、 nil 的问题

      摘要: 你有没有过这样的经历,就是界面上显示出类似<null>.(null)这样一些东西,有时候还会莫名其妙的闪退.反反复复真是曰了犬,今天来总结一下这个问题的解决方法 前段时间开发过 ...

  4. Windows10:Opencv4.0+Opencv4.0.1_contrib编译

    操作系统:windows10 64bit 已安装工具:VS2017 64bit,cmake3.12bit. 安装Cmake:到cmake下载3.12及以上版本,64bit, 选择windows下的安装 ...

  5. Spring Boot 微信-验证服务器有效性【转】

    转:https://blog.csdn.net/jeikerxiao/article/details/68064145 概述 接入微信公众平台开发,开发者需要按照如下步骤完成: 在自己服务器上,开发验 ...

  6. MySQL数据库安装配置步骤详解

    MYSQL的安装 1.打开下载的mysql安装文件mysql-5.5.27-win32.zip,双击解压缩,运行“setup.exe”. 2.选择安装类型,有“Typical(默认)”.“Comple ...

  7. 【Java】集合遍历--List和Map的多种遍历方式

    1. List的两种遍历方式 package com.nova.test; import java.util.ArrayList; import java.util.Iterator; import ...

  8. 如何判断一个 APP页面是否是H5页面(转载)

    1.无网络断开网络,显示404或则错误页面的是H5 2.页面布局a.在手机设置.开发者选项中开启显示布局边界功能:b.进入应用查看布局边界:c.原生应用可以看到各个控件的布局边界,H5只有整个页面的一 ...

  9. 基于C语言的面向对象编程

    嵌入式软件开发中,虽然很多的开发工具已经支持C++的开发,但是因为有时考虑运行效率和编程习惯,还是有很多人喜欢用C来开发嵌入式软件.Miro Samek说:"我在开发现场发现,很多嵌入式软件 ...

  10. TCP/IP协议族、版本以及编址机制

    TCP/IP协议族简称TCP/IP.这么命名是因为该协议家族中的两个核心协议:TCP(传输控制协议)和IP(网际协议),为该家族中最早通过的标准.TCP/IP提供点对点的链接机制,将数据应该如何封装, ...