将Integer源码看了一遍,最大的感觉就是位操作用的比较多,有些算法也不懂,不明白为什么要那么写;绝大部分也是看懂了的,有些地方写的非常的好,非常的巧妙,真是佩服那些人的智慧;例如在计算int整数的位数时计算方法时的算法,又如在将int转换成String时的算法,真的是惊叹!
注:面试常常问到的两个Integer比较问题如下
(引用)JVM会自动维护八种基本类型的常量池,int常量池中初始化-128~127的范围,所以当为Integer i=127时,在自动装箱过程中是取自常量池中的数值,而当Integer i=128时,128不在常量池范围内,所以在自动装箱过程中需new 128,所以地址不一样。源码中的代码如下:
// 传入int值,返回integer对象
public static Integer valueOf(int i) {
// IntegerCache.low = -128;IntegerCache.high = 127;这两个数据在Integer的内部类IntegerCache中可以看到
// 这里看出,在[-128, 127]之间的时候去IntegerCache.cache中拿数据,
// 在IntegerCache初始化的时候有一个for循环将[-128,127]存到cache[]中
// 在[-128, 127]之外就会新new一个对象,造成地址不一样
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
也许有人问为什么会调用valueOf而不是Integer构造函数,自动装箱的时候是调用valueOf(int i),即类似于Integer x = 10,的时候调用valueOf;而Integer y = new Integer(10); 则是调用构造函数,测试案例如下:
Integer a = new Integer(125);
Integer b = new Integer(125);
System.out.println((a == b));
// 返回false
从下面valueOf的注释也可以进一步说明:
Returns an {@code Integer} instance representing the specified {@code int} value.
If a new {@code Integer} instance is not required,
this method should generally be used in preference to the constructor {@link#Integer(int)},
as this method is likely to yield significantly better
space and time performance by caching frequently requested values.
--------翻译如下--------------------------------------------------
返回表示指定的{@code int}值的{@code Integer}实例。
如果不需要新的{@code Integer}实例,通常应该优先使用此方法,
而不是构造函数{@link #Integer(int)},
因为此方法可能通过频繁缓存产生明显更好的空间和时间性能 要求的价值。
在比较Integer包装数据类型的时候建议使用equals,compare,compareTo,或者是先转化成int基本数据类型后使用==比较,而实际上equals, compare方法内都是将数据转成int数据后使用==进行比较,compareTo调用的是compare方法
Integer源码如下:
//源码
package java.lang;
import java.lang.annotation.Native;
public final class Integer extends Number implements Comparable<Integer> {
// Integer的最小值
@Native public static final int MIN_VALUE = 0x80000000;
// Integer的最大值
@Native public static final int MAX_VALUE = 0x7fffffff;
//类原始类型 int的 类实例。
@SuppressWarnings("unchecked")
public static final Class<Integer> TYPE = (Class<Integer>) Class.getPrimitiveClass("int");
// 36个字符,数字与小写字母
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'
};
// i:需要转化的数据; radix:进制,
// 将数字i用radix进制表示, 然后转化为字符串
public static String toString(int i, int radix) {
// 判断进制的范围,不能是在规定的范围之外,如果在进制外,则设置为十进制
if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
radix = 10;
// 如果是十进制,直接将数据转化为字符串返回
if (radix == 10) {
return toString(i);
}
// 最多存放的位数
char buf[] = new char[33];
// if 是否是负数
boolean negative = (i < 0);
int charPos = 32;
// i为非负数,就将i变成负数, i为负数,i不变
if (!negative) {
i = -i;
}
// 将用进制表示的数存储在buf中
while (i <= -radix) {
buf[charPos--] = digits[-(i % radix)];
i = i / radix;
}
buf[charPos] = digits[-i];
// i为负数,加上-号
if (negative) {
buf[--charPos] = '-';
}
// 将有数据的buf截取,并返回一个新的字符串
return new String(buf, charPos, (33 - charPos));
}
// i:需要转化的数据; radix:进制,
// 将数字i用radix进制表示, 然后转化为无符号型字符串
public static String toUnsignedString(int i, int radix) {
return Long.toUnsignedString(toUnsignedLong(i), radix);
}
// 将i用无符号16进制表示,然后转化为字符串
public static String toHexString(int i) {
return toUnsignedString0(i, 4);
}
// 将i用无符号8进制表示,然后转化为字符串
public static String toOctalString(int i) {
return toUnsignedString0(i, 3);
}
// 将i用无符号2进制表示,然后转化为字符串
public static String toBinaryString(int i) {
return toUnsignedString0(i, 1);
}
// 私有方法,具体实现前面三个,无符号转化字符串
private static String toUnsignedString0(int val, int shift) {
// 计算出value所占的位数, 32 - 高位0占的位数
int mag = Integer.SIZE - Integer.numberOfLeadingZeros(val);
// 计算出,字符串魅族长度
int chars = Math.max(((mag + (shift - 1)) / shift), 1);
char[] buf = new char[chars];
// 将转化后的数据放入到buf中
formatUnsignedInt(val, shift, buf, 0, chars);
return new String(buf, true);
}
/**
* 返回长度并将缓冲数据放入到buf中
* @param val 需要转化的数字
* @param shift 将基数的log2移位到格式中(4表示十六进制,3表示八进制,1表示二进制)
* @param buf 缓冲字符数组,用于存储转化后的数据
* @param offset 开始的下标, 方法只在toUnsignedString0中调用一次, 因此为0
* @param len 数组buf的长度
* @return
*/
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 {
buf[offset + --charPos] = Integer.digits[val & mask];
val >>>= shift;
} while (val != 0 && charPos > 0);
return charPos;
}
// 数组下标的十位 例: degitTens[10] = '1' degitTens[76] = '7'
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',
} ;
// 数组下标的个位 例: DigitOnes[16] = '6' DigitOnes[29] = '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',
} ;
// 将数据i转化为字符串
public static String toString(int i) {
if (i == Integer.MIN_VALUE)
return "-2147483648";
// 计算出i的位数,
int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i);
// 创建一个缓冲字符数组buf用来接收
char[] buf = new char[size];
getChars(i, size, buf);
return new String(buf, true);
}
// 将数字i转化成无符号字符串
public static String toUnsignedString(int i) {
// 实际上是调用的Long中的toString()方法,
return Long.toString(toUnsignedLong(i));
}
// 将i转化为字符串,存在缓冲区buf中,
/**
* 将i转化为字符数组,并放入缓冲buf中
* @param i 需要转化的整数
* @param index buf的size
* @param buf 缓冲字符串
*/
static void getChars(int i, int index, char[] buf) {
int q, r;
int charPos = index;
// i的符号
char sign = 0;
// 将i转化为正数进行计算
if (i < 0) {
sign = '-';
i = -i;
}
// 每次迭代生成两位数
// 65536 --> 1 0000 0000 0000 0000
while (i >= 65536) {
q = i / 100;
// r = i - (q * 100);
// 2^6 + 2^5 + 2^2 = 100
r = i - ((q << 6) + (q << 5) + (q << 2));
i = q;
// 将小的位放在字符数据的高位,便于后面截取
buf [--charPos] = DigitOnes[r];
buf [--charPos] = DigitTens[r];
}
// 通过快速模式下降到较小的数字
for (;;) {
q = (i * 52429) >>> (16+3);
r = i - ((q << 3) + (q << 1)); // r = i-(q*10) ...
buf [--charPos] = digits [r];
i = q;
if (i == 0) break;
}
// sign != 0 说明传入的数为负数,将-号加入到buf中
if (sign != 0) {
buf [--charPos] = sign;
}
}
// 定义一个int数组,用于比较计算整数所占的长度, 该方法只在stringSize中使用
final static int [] sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999,
99999999, 999999999, Integer.MAX_VALUE };
// 用于计算整数x的长度, 这里写的非常的巧妙
static int stringSize(int x) {
for (int i=0; ; i++)
if (x <= sizeTable[i])
return i+1;
}
// 将数字字符串,radix是指的s是多少进制, 最终会以十进制输出
// Integer.parseInt("11", 2) --> 3
// Integer.parseInt("f", 16) --> 15
public static int parseInt(String s, int radix)
throws NumberFormatException
{
// 对传入参数进行校验,抛出异常
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;
// len > 0为了防止 s="";抛异常
if (len > 0) {
// 获取传入字符串的第一位,确定正负
char firstChar = s.charAt(0);
if (firstChar < '0') {
//
if (firstChar == '-') {
negative = true;
limit = Integer.MIN_VALUE;
} else if (firstChar != '+')
// 不是"-"或者"+" 就抛异常
throw NumberFormatException.forInputString(s);
// len == 1 说明只有"+"或者"-"抛异常
if (len == 1)
throw NumberFormatException.forInputString(s);
i++;
}
// 余数
multmin = limit / radix;
while (i < len) {
// 获取到字符对应的整数
digit = Character.digit(s.charAt(i++),radix);
// 对数据
if (digit < 0) {
throw NumberFormatException.forInputString(s);
}
if (result < multmin) {
throw NumberFormatException.forInputString(s);
}
// result增加 --> like result = result * 10(十进制)
result *= radix;
if (result < limit + digit) {
throw NumberFormatException.forInputString(s);
}
// 这里是-=而不是+=,因为result第一轮循环时就是负数
// 最后返回时,negative(表示负)为true返回result,否则返回-result
result -= digit;
}
} else {
throw NumberFormatException.forInputString(s);
}
return negative ? result : -result;
}
// 将数字字符串转化成int型数据,不指定转化进制,默认10进制
public static int parseInt(String s) throws NumberFormatException {
return parseInt(s,10);
}
// 无符号转化, radix是指的是s的进制,看parseInt的注释
public static int parseUnsignedInt(String s, int radix)
throws NumberFormatException {
// 判断是否为空,抛异常
if (s == null) {
throw new NumberFormatException("null");
}
int len = s.length();
// len > 0为了防止 s="";抛异常
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 || // Character.MAX_RADIX中的Integer.MAX_VALUE是6位数
(radix == 10 && len <= 9) ) { // 基数10中的Integer.MAX_VALUE是10位数
return parseInt(s, radix);
} else {
// 其它的转化就调用LongparseLong(String s, int radix)
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);
}
}
// 无符号转化,只传转化的字符串,默认以十进制转化
public static int parseUnsignedInt(String s) throws NumberFormatException {
return parseUnsignedInt(s, 10);
}
// 传入一个数字字符串,radix指的是s的进制,看parseInt的注释
public static Integer valueOf(String s, int radix) throws NumberFormatException {
return Integer.valueOf(parseInt(s,radix));
}
// 传入一个数字字符串,不指定进制转换成integer,默认以十进制转化
public static Integer valueOf(String s) throws NumberFormatException {
return Integer.valueOf(parseInt(s, 10));
}
// 内部类 整数缓存
private static class IntegerCache {
static final int low = -128;
static final int high;
static final Integer cache[];
static {
// 高值可以由属性配置
int h = 127;
// 整数缓存高位值
String integerCacheHighPropValue =
sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
if (integerCacheHighPropValue != null) {
try {
// 高位不为空转化为int
int i = parseInt(integerCacheHighPropValue);
i = Math.max(i, 127);
// 最大数组大小为Integer.MAX_VALUE
h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
} catch( NumberFormatException nfe) {
}
}
high = h;
cache = new Integer[(high - low) + 1];
int j = low;
// 初始化时将[-128, 127]缓存到cache[]中,自动装箱的时候,直接到这里拿数据
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
// 范围 [-128, 127]
assert IntegerCache.high >= 127;
}
private IntegerCache() {}
}
// 传入int值,返回integer对象
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
// 定义一个常量用于接收传入的int对象
private final int value;
// 构造函数,传入int值
public Integer(int value) {
this.value = value;
}
// 构造函数,传入数字字符串,这里先调用parseInt(s, 10),以十进制转化为int类型
public Integer(String s) throws NumberFormatException {
this.value = parseInt(s, 10);
}
// int类型转成其它的类型
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;
}
public String toString() {
return toString(value);
}
// 计算值的hashCode
@Override
public int hashCode() {
return Integer.hashCode(value);
}
// 数字的hashCode就是其本身
public static int hashCode(int value) {
return value;
}
// 通过equals比较两数
public boolean equals(Object obj) {
if (obj instanceof Integer) {
return value == ((Integer)obj).intValue();
}
return false;
}
// 确定具有指定名称的系统属性的整数值。key-value
public static Integer getInteger(String nm) {
return getInteger(nm, null);
}
// 确定具有指定名称的系统属性的整数值。key-value
public static Integer getInteger(String nm, int val) {
Integer result = getInteger(nm, null);
// val 表示传入一个默认值,如果系统属性的整数值为空,返回默认的传入的val
return (result == null) ? Integer.valueOf(val) : result;
}
// 确定具有指定名称的系统属性的整数值, key-value
public static Integer getInteger(String nm, Integer val) {
String v = null;
try {
// 通过key获取到value
v = System.getProperty(nm);
} catch (IllegalArgumentException | NullPointerException e) {
}
if (v != null) {
try {
// 这里没有返回成功,就会在最后返回默认的val
return Integer.decode(v);
} catch (NumberFormatException e) {
}
}
return val;
}
// 将String解码为Integer
public static Integer decode(String nm) throws NumberFormatException {
// 默认十进制
int radix = 10;
// 下标
int index = 0;
// 默认为正数
boolean negative = false;
// 缓存结果
Integer result;
if (nm.length() == 0)
throw new NumberFormatException("Zero length string");
// 处理字符串的第一位是'+'或者'-'
char firstChar = nm.charAt(0);
if (firstChar == '-') {
negative = true;
index++;
} else if (firstChar == '+')
index++;
// 处理十六进制, 八进制
if (nm.startsWith("0x", index) || nm.startsWith("0X", index)) {
index += 2;
radix = 16;
}
else if (nm.startsWith("#", index)) {
index ++;
radix = 16;
}
else if (nm.startsWith("0", index) && nm.length() > 1 + index) {
index ++;
radix = 8;
}
// 正负的标志位置错误
if (nm.startsWith("-", index) || nm.startsWith("+", index))
throw new NumberFormatException("Sign character in wrong position");
try {
// 对字符串去掉标志位解析
result = Integer.valueOf(nm.substring(index), radix);
result = negative ? Integer.valueOf(-result.intValue()) : result;
} catch (NumberFormatException e) {
String constant = negative ? ("-" + nm.substring(index))
: nm.substring(index);
result = Integer.valueOf(constant, radix);
}
return result;
}
// 比较两个int数的大小,返回-1、0、1, 实际调用的是compare(int x, int y)方法
public int compareTo(Integer anotherInteger) {
return compare(this.value, anotherInteger.value);
}
// 比较两个int数的大小,返回-1、0、1
public static int compare(int x, int y) {
return (x < y) ? -1 : ((x == y) ? 0 : 1);
}
// 比较两个 int值以数字方式将值视为无符号
// Integer.compareUnsigned(10, -11) 返回 -1
public static int compareUnsigned(int x, int y) {
return compare(x + MIN_VALUE, y + MIN_VALUE);
}
// 将整数x转化为无符号数
public static long toUnsignedLong(int x) {
return ((long) x) & 0xffffffffL;
}
// 返回将第一个参数除以第二个参数的无符号商,其中每个参数和结果被解释为无符号值。
public static int divideUnsigned(int dividend, int divisor) {
// 代替棘手的代码,现在只需使用长算术。
return (int)(toUnsignedLong(dividend) / toUnsignedLong(divisor));
}
// 返回将第一个参数除以第二个参数的无符号商,其中每个参数和结果被解释为无符号值。
public static int remainderUnsigned(int dividend, int divisor) {
// 代替棘手的代码,现在只需使用长算术。
return (int)(toUnsignedLong(dividend) % toUnsignedLong(divisor));
}
// Bit twiddling
@Native public static final int SIZE = 32;
public static final int BYTES = SIZE / Byte.SIZE;
// 返回“最左侧”的位置在指定的一个位int值
// Integer.highestOneBit(129) --> 128
// Integer.highestOneBit(127) --> 64
// 129 --> 0100 0001 返回 128 --> 0100 0000
// 127 --> 0011 1111 返回 64 --> 0010 0000
public static int highestOneBit(int i) {
// HD, Figure 3-1
i |= (i >> 1);
i |= (i >> 2);
i |= (i >> 4);
i |= (i >> 8);
i |= (i >> 16);
return i - (i >>> 1);
}
// 返回“最右侧”的位置在指定的一个位int值
// 120 --> 0011 1000 返回 8 --> 0000 1000
// 129 --> 0100 0001 返回 1 --> 0000 0001
public static int lowestOneBit(int i) {
return i & -i;
}
// ?????????????????
// 最高位之前的零 的位数, 不理解代码的算法, 后面有空填坑
public static int numberOfLeadingZeros(int i) {
// i 为0, 所有的2进制都是0,直接返回32
if (i == 0)
return 32;
// n是i表示为2进制有效的位数
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;
}
// ?????????????????
// 最末尾的零 的位数, 不理解代码的算法, 后面有空填坑
public static int numberOfTrailingZeros(int i) {
int y;
if (i == 0) return 32;
int n = 31;
// 如果 i > 2 ^16 --> n = n - 16 = 31 - 16 = 15
y = i <<16; if (y != 0) { n = n -16; i = y; }
y = i << 8; if (y != 0) { n = n - 8; i = y; }
y = i << 4; if (y != 0) { n = n - 4; i = y; }
y = i << 2; if (y != 0) { n = n - 2; i = y; }
return n - ((i << 1) >>> 31);
}
// 返回指定的int值的二进制补码二进制表示中的int数
public static int bitCount(int i) {
// HD, Figure 5-2
i = i - ((i >>> 1) & 0x55555555);
i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
i = (i + (i >>> 4)) & 0x0f0f0f0f;
i = i + (i >>> 8);
i = i + (i >>> 16);
return i & 0x3f;
}
// 通过将指定的int值的二进制补码二进制表示旋转指定的位数 int值。
// Integer.rotateLeft(8, 5) --> 8*2^5
public static int rotateLeft(int i, int distance) {
return (i << distance) | (i >>> -distance);
}
// 通过将指定的int值的二进制补码二进制表示旋转指定的位数 int值。
// Integer.rotateRight(64, 5) --> 64/(2^5)
public static int rotateRight(int i, int distance) {
return (i >>> distance) | (i << -distance);
}
// 返回由指定的二进制补码表示反转位的顺序而获得的值 int值。
public static int reverse(int i) {
// HD, Figure 7-1
i = (i & 0x55555555) << 1 | (i >>> 1) & 0x55555555;
i = (i & 0x33333333) << 2 | (i >>> 2) & 0x33333333;
i = (i & 0x0f0f0f0f) << 4 | (i >>> 4) & 0x0f0f0f0f;
i = (i << 24) | ((i & 0xff00) << 8) |
((i >>> 8) & 0xff00) | (i >>> 24);
return i;
}
// 求整数i的符号。负零正分别返回-1、0、1
public static int signum(int i) {
return (i >> 31) | (-i >>> 31);
}
// 返回反转指定的二进制补码表示的字节顺序而获得的值 int值。
public static int reverseBytes(int i) {
return ((i >>> 24) ) |
((i >> 8) & 0xFF00) |
((i << 8) & 0xFF0000) |
((i << 24));
}
// 求和
public static int sum(int a, int b) {
return a + b;
}
// 求两个数中的大值
public static int max(int a, int b) {
return Math.max(a, b);
}
// 求两个数中的小值
public static int min(int a, int b) {
return Math.min(a, b);
}
@Native private static final long serialVersionUID = 1360826667806852920L;
}
故不积跬步,无以至千里;不积小流,无以成江海。