上节我们介绍过JDK源码-Float类
本节我们介绍Integer类,Integer 类在对象中包装了一个基本类型 int 的值。Integer 类对象包含一个 int 类型的字段。此外,该类提供了多个方法,能在 int 类型和 String 类型之间互相转换,还提供了处理 int 类型时非常有用的其他一些常量和方法。
一、实现方法
Integer类是基本类型int的包装类,继承了Number类,并且实现了Comparable接口
public final class Integer extends Number implements Comparable<Integer>
二、构造方法
//构造一个新分配的 Integer 对象,它表示指定的 int 值
public Integer(int value) {
this.value = value;
}
//构造一个新分配的 Integer 对象,它表示 String 参数所指示的 int 值。
public Integer(String s) throws NumberFormatException {
this.value = parseInt(s, 10);
}
用来存放Integer对象那int对应的值。
private final int value;
二、常用常量
//值为 -2^31 的常量,它表示 int 类型能够表示的最小值
@Native public static final int MIN_VALUE = 0x80000000;
//值为 2^31-1 的常量,它表示 int 类型能够表示的最大值
@Native public static final int MAX_VALUE = 0x7fffffff;
//表示基本类型 int 的 Class 实例
@SuppressWarnings("unchecked")
public static final Class<Integer> TYPE = (Class<Integer>) Class.getPrimitiveClass("int");
//所有可能的char字符数组
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'
};
三、常用方法
toString toXXXString 系列
//静态方法根据指定进制返回一个String,如果基数小于 Character.MIN_RADIX 或者大于 Character.MAX_RADIX,默认设置为10。如果是负数 第一个符号位负号 '-' ('\u002D'),如果不是负数,将不会有符号剩下的字符表示第一个参数的大小如果大小是0 由字符 '0' ('\u0030') 表示,否则用来表示数值的第一个字符不会是0
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];
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] = '-';
}
return new String(buf, charPos, (33 - 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];
getChars(i, size, buf);
return new String(buf, true);
}
//静态方法以十六进制(基数 16)无符号整数形式返回一个整数参数的字符串表示形式
public static String toHexString(int i) {
return toUnsignedString0(i, 4);
}
//静态方法以八进制(基数 8)无符号整数形式返回一个整数参数的字符串表示形式
public static String toOctalString(int i) {
return toUnsignedString0(i, 3);
}
//静态方法以二进制(基数 2)无符号整数形式返回一个整数参数的字符串表示形式
public static String toBinaryString(int i) {
return toUnsignedString0(i, 1);
}
//私有方法用于转换为无符号形式
private static String toUnsignedString0(int val, int shift) {
int mag = Integer.SIZE - Integer.numberOfLeadingZeros(val);
int chars = Math.max(((mag + (shift - 1)) / shift), 1);
char[] buf = new char[chars];
formatUnsignedInt(val, shift, buf, 0, chars);
return new String(buf, true);
}
parseInt方法
//静态方法使用第二个参数指定的基数(进制),将字符串参数解析为有符号的整数除了第一个字符可以是用来表示负值的 ASCII 减号 '-' ('\u002D’),加号'+' ('\u002B') 外字符串中的字符必须都是指定基数的数字
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;
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) {
// Accumulating negatively avoids surprises near MAX_VALUE
digit = Character.digit(s.charAt(i++),radix);
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;
}
} else {
throw NumberFormatException.forInputString(s);
}
return negative ? result : -result;
}
//静态方法static int parseInt(String s, int radix) 的十进制简化形式
public static int parseInt(String s) throws NumberFormatException {
return parseInt(s,10);
}
valueOf方法
核心逻辑在第一个valueOf方法中,因为IntegerCache缓存了[low,high]值的Integer对象,对于在范围内的直接从IntegerCache的数组中获取对应的Integer对象即可,而在范围外的则需要重新实例化了。
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
public static Integer valueOf(String s) throws NumberFormatException {
return Integer.valueOf(parseInt(s, 10));
}
public static Integer valueOf(String s, int radix) throws NumberFormatException {
return Integer.valueOf(parseInt(s,radix));
}
IntegerCache内部类
IntegerCache是Integer的一个内部类,它包含了int可能值的Integer数组,默认范围是[-128,127],它不会像Byte类将所有可能值缓存起来,因为int类型范围很大,将它们全部缓存起来代价太高,而Byte类型就是从-128到127,一共才256个。所以这里默认只实例化256个Integer对象,当Integer的值范围在[-128,127]时则直接从缓存中获取对应的Integer对象,不必重新实例化。这些缓存值都是静态且final的,避免重复的实例化和回收。另外我们可以改变这些值缓存的范围,再启动JVM时通过-Djava.lang.Integer.IntegerCache.high=xxx就可以改变缓存值的最大值,比如-Djava.lang.Integer.IntegerCache.high=500则会缓存[-128,500]。
private static class IntegerCache {
static final int low = -128;
static final int high;
static final Integer cache[];
static {
// high value may be configured by property
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() {}
}
decode方法
decode方法主要作用是解码字符串转成Integer型,比如Integer.decode(“11”)的结果为11;Integer.decode(“0x11”)和Integer.decode("#11")结果都为17,因为0x和#开头的会被处理成十六进制;Integer.decode(“011”)结果为9,因为0开头会被处理成8进制。
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;
}
XXXValue系列
强制类型转换的形式,
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;
}
hashCode()
直接返回 value 的 int 类型的值。
public int hashCode() {
return Integer.hashCode(value);
}
public static int hashCode(int value) {
return value;
}
equals(Object obj)
比较是否相同时先判断是不是Integer类型再比较值。
public boolean equals(Object obj) {
if (obj instanceof Integer) {
return value == ((Integer)obj).intValue();
}
return false;
}