说明:
Integer类包装一个对象中的原始类型int的值。 类型为Integer的对象包含一个单一字段,其类型为int 。此外,该类还提供了一些将int转换为String和String转换为int ,以及在处理int时有用的其他常量和方法。int 数据类型是32位、有符号的以二进制补码表示的整数。
类图结构:
源码解析:
package java.lang;
public final class Integer extends Number implements Comparable<Integer> {
/**
* 最小值是 -2,147,483,648(-2^31),0x80000000是最小值的16进制;
*/
@Native public static final int MIN_VALUE = 0x80000000;
/**
* 最大值是 2,147,483,647(2^31 - 1),0x7fffffff 是该最大值的16进制。
*/
@Native public static final int MAX_VALUE = 0x7fffffff;
/**
* 类原始类型 int的 类实例。
*/
@SuppressWarnings("unchecked")
public static final Class<Integer> TYPE = (Class<Integer>) Class.getPrimitiveClass("int");
/**
* digits数组用于表示数字的所有可能的字符,因为int支持从2进制到36进制,所以这里需要有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'
};
/**
* 返回由第二个参数指定的基数中的第一个参数的字符串表示形式。
*/
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] = '-';
}
return new String(buf, charPos, (33 - charPos));
}
/**
* 以第二个参数指定的基数中的无符号整数值返回第一个参数的字符串表示形式。
* @since 1.8
*/
public static String toUnsignedString(int i, int radix) {
return Long.toUnsignedString(toUnsignedLong(i), radix);
}
/**
* 将整数转换成16进制的字符串。
* @since JDK1.0.2
*/
public static String toHexString(int i) {
return toUnsignedString0(i, 4);
}
/**
* 将整数转换成8进制的字符串。
* @since JDK1.0.2
*/
public static String toOctalString(int i) {
return toUnsignedString0(i, 3);
}
/**
* 将整数转换成2进制的字符串。
* @since JDK1.0.2
*/
public static String toBinaryString(int i) {
return toUnsignedString0(i, 1);
}
/**
* 该方法会先计算转换成对应进制需要的字符数,然后再通过formatUnsignedInt方法来填充字符数组,该方法做的事情就是使用进制之间的转换方法(前面有提到过)来获取对应的字符。
*/
private static String toUnsignedString0(int val, int shift) {
// assert shift > 0 && shift <=5 : "Illegal shift value";
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);
// Use special constructor which takes over "buf".
return new String(buf, true);
}
/**
* Format a long (treated as unsigned) into a character buffer.
* @param val the unsigned int to format
* @param shift the log2 of the base to format in (4 for hex, 3 for octal, 1 for binary)
* @param buf the character buffer to write to
* @param offset the offset in the destination buffer to start at
* @param len the number of characters to write
* @return the lowest character location used
*/
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;
}
/**
* DigitTens和DigitOnes两个数组放到一起讲更好理解,它们主要用于获取0到99之间某个数的十位和个位,比如24,通过DigitTens数组直接取出来十位为2,而通过DigitOnes数组取出来个位为4。
*/
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',
} ;
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',
} ;
/**
* 将int类型转换成String类型。
*/
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);
}
/**
* 返回一个参数的字符串表示形式,作为一个无符号的十进制值。
* @since 1.8
*/
public static String toUnsignedString(int i) {
return Long.toString(toUnsignedLong(i));
}
/**
* 该方法主要做的事情是将某个int型数值放到char数组里面,比如把357按顺序放到char数组中。这里面处理用了较多技巧,int高位的两个字节和低位的两个字节分开处理,while (i >= 65536)部分就是处理高位的两个字节,每次处理2位数,这里有个特殊的地方((q << 6) + (q << 5) + (q << 2))其实等于q*100,DigitTens和DigitOnes数组前面已经讲过它的作用了,用来获取十位和个位。再看接下去的低位的两个字节怎么处理,其实本质也是求余思想,但又用了一些技巧,比如(i * 52429) >>> (16+3)其实约等于i/10,((q << 3) + (q << 1))其实等于q*10,然后再通过digits数组获取到对应的字符。可以看到低位处理时它尽量避开了除法,取而代之的是用乘法和右移来实现,可见除法是一个比较耗时的操作,比起乘法和移位。另外也可以看到能用移位和加法来实现乘法的地方也尽量不用乘法,这也说明乘法比起它们更加耗时。而高位处理时没有用移位是因为做乘法后可能会溢出。
*/
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
while (i >= 65536) {
q = i / 100;
// really: r = i - (q * 100);
r = i - ((q << 6) + (q << 5) + (q << 2));
i = q;
buf [--charPos] = DigitOnes[r];
buf [--charPos] = DigitTens[r];
}
// Fall thru to fast mode for smaller numbers
// assert(i <= 65536, i);
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;
}
if (sign != 0) {
buf [--charPos] = sign;
}
}
/**
* sizeTable数组主要用在判断一个int型数字对应字符串的长度。比如stringSize(int x) 方法,这种方法可以高效得到对应字符串长度,避免了使用除法或求余等操作。
* @since 1.8
*/
final static int [] sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999,
99999999, 999999999, Integer.MAX_VALUE };
// Requires positive x
static int stringSize(int x) {
for (int i=0; ; i++)
if (x <= sizeTable[i])
return i+1;
}
/**
* 将字符串参数解析为第二个参数指定的基数中的有符号整数。
*/
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;
}
/**
* 将字符串参数解析为无符号十进制整数。
*/
public static int parseInt(String s) throws NumberFormatException {
return parseInt(s,10);
}
/**
* 将字符串参数解析为第二个参数指定的基数中的无符号整数。
* @since 1.8
*/
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);
}
}
/**
* 将字符串参数解析为无符号十进制整数。
* @since 1.8
*/
public static int parseUnsignedInt(String s) throws NumberFormatException {
return parseUnsignedInt(s, 10);
}
/**
* 以第二个参数指定的基数中的无符号整数值返回第一个参数的字符串表示形式。
*/
public static Integer valueOf(String s, int radix) throws NumberFormatException {
return Integer.valueOf(parseInt(s,radix));
}
/**
* 将String转化成Integer类型
*/
public static Integer valueOf(String s) throws NumberFormatException {
return Integer.valueOf(parseInt(s, 10));
}
/**
* IntegerCache是Integer的一个内部类,它包含了int可能值的Integer数组,默认范围是[-128,127],它不会像Byte类将所有可能值缓存起来,因为int类型范围很大,将它们全部缓存起来代价太高,而Byte类型就是从-128到127,一共才256个。所以这里默认只实例化256个Integer对象,当Integer的值范围在[-128,127]时则直接从缓存中获取对应的Integer对象,不必重新实例化。这些缓存值都是静态且final的,避免重复的实例化和回收。
*/
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() {}
}
/**
* 将int类型转化成Integer类型。
* @since 1.5
*/
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
/**
* The value of the {@code Integer}.
*
* @serial
*/
private final int value;
/**
* 构造一个新分配的 Integer对象,该对象表示指定的 int值。
*/
public Integer(int value) {
this.value = value;
}
/**
* 将int类型的值强转成byte。
*/
public byte byteValue() {
return (byte)value;
}
/**
* 将int类型的值强转成short。
*/
public short shortValue() {
return (short)value;
}
/**
* 获取int的值。
*/
public int intValue() {
return value;
}
/**
* 将int类型的值强转成long。
*/
public long longValue() {
return (long)value;
}
/**
* 将int类型的值强转成float。
*/
public float floatValue() {
return (float)value;
}
/**
* 将int类型的值强转成double。
*/
public double doubleValue() {
return (double)value;
}
/**
* 将int类型的值强转成String。
*/
public String toString() {
return toString(value);
}
/**
* 返回这个 Integer的哈希码
*/
@Override
public int hashCode() {
return Integer.hashCode(value);
}
/**
* 返回值为int的哈希码; 兼容Integer.hashCode() 。
* @since 1.8
*
* @return a hash code value for a {@code int} value.
*/
public static int hashCode(int value) {
return value;
}
public boolean equals(Object obj) {
if (obj instanceof Integer) {
return value == ((Integer)obj).intValue();
}
return false;
}
/**
* String 类型转Integer类型
*/
public static Integer getInteger(String nm) {
return getInteger(nm, null);
}
/**
* 确定具有指定名称的系统属性的整数值
*/
public static Integer getInteger(String nm, int val) {
Integer result = getInteger(nm, null);
return (result == null) ? Integer.valueOf(val) : result;
}
public static Integer getInteger(String nm, Integer val) {
String v = null;
try {
v = System.getProperty(nm);
} catch (IllegalArgumentException | NullPointerException e) {
}
if (v != null) {
try {
return Integer.decode(v);
} catch (NumberFormatException e) {
}
}
return val;
}
/**
*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);
// Handle sign, if present
if (firstChar == '-') {
negative = true;
index++;
} else if (firstChar == '+')
index++;
// Handle radix specifier, if present
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) {
// If number is Integer.MIN_VALUE, we'll end up here. The next line
// handles this case, and causes any genuine format error to be
// rethrown.
String constant = negative ? ("-" + nm.substring(index))
: nm.substring(index);
result = Integer.valueOf(constant, radix);
}
return result;
}
/**
* 比较两 Integer对象数值。
*/
public int compareTo(Integer anotherInteger) {
return compare(this.value, anotherInteger.value);
}
/**
* 比较两个 int数字值。
* @since 1.7
*/
public static int compare(int x, int y) {
return (x < y) ? -1 : ((x == y) ? 0 : 1);
}
/**
* 比较两个 int值,以数值方式将值视为无符号。
*/
public static int compareUnsigned(int x, int y) {
return compare(x + MIN_VALUE, y + MIN_VALUE);
}
public static long toUnsignedLong(int x) {
return ((long) x) & 0xffffffffL;
}
public static int divideUnsigned(int dividend, int divisor) {
// In lieu of tricky code, for now just use long arithmetic.
return (int)(toUnsignedLong(dividend) / toUnsignedLong(divisor));
}
public static int remainderUnsigned(int dividend, int divisor) {
// In lieu of tricky code, for now just use long arithmetic.
return (int)(toUnsignedLong(dividend) % toUnsignedLong(divisor));
}
/**
* The number of bits used to represent an {@code int} value in two's
* complement binary form.
*
* @since 1.5
*/
@Native public static final int SIZE = 32;
/**
* The number of bytes used to represent a {@code int} value in two's
* complement binary form.
*
* @since 1.8
*/
public static final int BYTES = SIZE / Byte.SIZE;
/**
*该方法返回i的二进制中最高位的1,其他全为0的值。比如i=10时,二进制即为1010,最高位的1,其他为0,则是1000。如果i=0,则返回0。如果i为负数则固定返回-2147483648,因为负数的最高位一定是1,即有1000,0000,0000,0000,0000,0000,0000,0000。这一堆移位操作是什么意思?其实也不难理解,将i右移一位再或操作,则最高位1的右边也为1了,接着再右移两位并或操作,则右边1+2=3位都为1了,接着1+2+4=7位都为1,直到1+2+4+8+16=31都为1,最后用i - (i >>> 1)自然得到最终结果。
* @since 1.5
*/
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);
}
/**
* 与highestOneBit方法对应,lowestOneBit获取最低位1,其他全为0的值。这个操作较简单,先取负数,这个过程需要对正数的i取反码然后再加1,得到的结果和i进行与操作,刚好就是最低位1其他为0的值了。
* @since 1.5
*/
public static int lowestOneBit(int i) {
// HD, Section 2-1
return i & -i;
}
/**
* 该方法返回i的二进制从头开始有多少个0。i为0的话则有32个0。这里处理其实是体现了二分查找思想的,先看高16位是否为0,是的话则至少有16个0,否则左移16位继续往下判断,接着右移24位看是不是为0,是的话则至少有16+8=24个0,直到最后得到结果。
* @since 1.5
*/
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;
}
/**
* 与前面的numberOfLeadingZeros方法对应,该方法返回i的二进制从尾开始有多少个0。它的思想和前面的类似,也是基于二分查找思想,详细步骤不再赘述。
* @since 1.5
*/
public static int numberOfTrailingZeros(int i) {
// HD, Figure 5-14
int y;
if (i == 0) return 32;
int n = 31;
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);
}
/**
* 该方法主要用于计算二进制数中1的个数。一看有点懵,都是移位和加减操作。它的核心思想就是先每两位一组统计看有多少个1,比如10011111则每两位有1、1、2、2个1,记为01011010,然后再算每四位一组看有多少个1,而01011010则每四位有2、4个1,记为00100100,接着每8位一组就为00000110,接着16位,32位,最终在与0x3f进行与运算,得到的数即为1的个数。
* @since 1.5
*/
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;
}
public static int rotateLeft(int i, int distance) {
return (i << distance) | (i >>> -distance);
}
public static int rotateRight(int i, int distance) {
return (i >>> distance) | (i << -distance);
}
/**
* 该方法即是将i进行反转,反转就是第1位与第32位对调,第二位与第31位对调,以此类推。它的核心思想是先将相邻两位进行对换,比如10100111对换01011011,接着再将相邻四位进行对换,对换后为10101101,接着将相邻八位进行对换,最后把32位中中间的16位对换,然后最高8位再和最低8位对换。
* @since 1.5
*/
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;
}
public static int signum(int i) {
// HD, Section 2-7
return (i >> 31) | (-i >>> 31);
}
/**
*返回反转指定的二进制补码表示的字节顺序而获得的值 int值。
*/
public static int reverseBytes(int i) {
return ((i >>> 24) ) |
((i >> 8) & 0xFF00) |
((i << 8) & 0xFF0000) |
((i << 24));
}
/**
* 取两个整数的和
* @since 1.8
*/
public static int sum(int a, int b) {
return a + b;
}
/**
* 取两个整数的最大值
* @since 1.8
*/
public static int max(int a, int b) {
return Math.max(a, b);
}
/**
* 返回两个整数之间较小的一个
* @since 1.8
*/
public static int min(int a, int b) {
return Math.min(a, b);
}
}