Integer
对象缓存
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() {}
}
从上面代码可以看出
-
指定返回类的数值必须缓存,
-
缓存最小值是 -128,最大值可以通过程序设置,如果不设置就是默认值 127
-
可以通过设置
java.lang.Integer.IntegerCache.high设置缓存的最大值。 -
缓存值存放在一个静态数组中。
-
如果定义的值在缓存中,无论怎么赋值,都是同一个 Integer 对象。
Integer a = 1;
Integer b = Integer.valueOf(1);
// a == b true;
构造 Integer 对象
方式一:通过构造器
public Integer(int value) {
this.value = value;
}
public Integer(String s) throws NumberFormatException {
this.value = parseInt(s, 10);
}
方式二:通过静态方法,最终都是通过构造器创建 Integer 对象
public static Integer valueOf(String s, int radix) throws NumberFormatException {
return Integer.valueOf(parseInt(s,radix));
}
public static Integer valueOf(String s) throws NumberFormatException {
return Integer.valueOf(parseInt(s, 10));
}
// 注意:如果值在缓存范围内,则从缓存数组中取值。
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
转字符串
(1)toString(int, int): String
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;
}
// int型的最大值为2147483647,最小值为 -2147483648;
// 如果将负数转为正数,最小值在转时会溢出,故使用负数来进行运行
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));
}
好的代码,本身就是说明解释,其他说明反而显得画蛇添足
-
如果进制不在规定范围内,默认采用 10 进制
-
如果是十进制,直接使用另一个 toString 方法
-
定义了一个容量为 33 的 char 数组,int 值存放,4 个字节,32 位,加一个正负号字符,共 33。
-
先判断数值正负,如果正数,先转为负数,根据进制进行运算,并把每次运算的结果放入定义好的 char 数组中(顺序是从后往前)。这里是主要的算法逻辑。
-
最后通过构建 String 对象,实现 Integer 转 String。
这里涉及到一个10进制转其他进制的一个方法。
如10进制转2进制,其他进制,把除数2改为对应进制就行:
789 = 1100010101(B) 789/2=394 余1 第10位 394/2=197 余0 第9位 197/2=98 余1 第8位 98/2=49 余0 第7位 49/2=24 余1 第6位 24/2=12 余0 第5位 12/2=6 余0 第4位 6/2=3 余0 第3位 3/2=1 余1 第2位 1/2=0 余1 第1位
转换为下面代码:
while (i <= -radix) {
// 根据radix取余,再从digits数组中取出radix下对应的字符,放入buf数组中,从尾部往前放
buf[charPos--] = digits[-(i % radix)];
// 一次取余后,进行除法运算得到下一个数,再循环取余。
i = i / radix;
}
// 最后一位,也即i的值,既是第一位
buf[charPos] = digits[-i];
(2)toUnsignedString(int, int): String
调用Long类函数,这里不做分析
(3)转进制格式方法
16进制:toHexString(int): String
8进制:toOctalString(int): String
2进制:toBinaryString(int): String
这个转换底层都是调用,toUnsignedString0(int val, int shift)方法
private static String toUnsignedString0(int val, int shift) {
// 计算出2进制数的位数
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);
}
/**
* 计算出一个2进制数,前面的0的个数
*/
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;
// 掩码,作用是与val进行&运算,保留最后
int mask = radix - 1;
do {
buf[offset + --charPos] = Integer.digits[val & mask];
val >>>= shift;
} while (val != 0 && charPos > 0);
return charPos;
}
具体参考https://blog.csdn.net/lianjiww/article/details/90183672
(4)toString(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);
}
-
如果是最小值,直接返回最小值的字符串格式
-
接着求 size,如果是负数,转正数,长度加一。关键 stringSize 函数
-
然后 getChars 将 i 转为对应的字符数组
-
使用 String 的构造器创建字符串。
stringSize 详解
final static int [] sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999,
99999999, 999999999, Integer.MAX_VALUE };
// 依次和sizeTable的数字比较,如果数小于比较数,则该位置的下标加1,既是长度。
static int stringSize(int x) {
for (int i=0; ; i++)
if (x <= sizeTable[i])
return i+1;
}
getChar解析
/**
* 思路:定义了一个char 数组,每次取数字最后一位,放入char数组最后一位。直到最顶位。
* 例如 数字23423435
* 如果数字大于65536, 每次想法获取后两位,35,剩下234234,满足条件,* 再次循环。
* 当数字小于65536,每次想法获取个位数,例如 2342 ,每次获取个位数。
*
*/
static void getChars(int i, int index, char[] buf) {
// 例如 678380 除以 100 来得到2个结果, q=6783 r=80
int q, r;
// 直接将index命名为charPos不行吗?为什么需要重新定义一个变量?多此一举
int charPos = index;
char sign = 0;
// 判断是否为负数。
if (i < 0) {
sign = '-';
i = -i;
}
// 如果数大于65536,则每次操作除以100,得到拆分后的2个部分。
// 例如 678380 除以 100 来得到2个结果, q=6783 r=80
// 每次循环,作用是取数字的后两位,来得到结果。
while (i >= 65536) {
q = i / 100;
// 等价于 r = i - q*100, 也即获取数字的后两位。
r = i - ((q << 6) + (q << 5) + (q << 2));
// 将去掉后两位的数字,在复制给i,再次进行循环。
i = q;
// 这里是获取到的数字后两位,结合DigitOnes和DigitTens找出十位数字以及个位数字的字符串形式。这里以获取的80为例
// 个位:第八排第一个数,就是0
buf [--charPos] = DigitOnes[r];
// 十位:第八排,无论个位数是几,十位始终是8,
buf [--charPos] = DigitTens[r];
}
// 数字小于65536,则采用除10来通过获取个位数来获取对应的字符
for (;;) {
// 含义是除10
q = (i * 52429) >>> (16+3);
// 这里相当于 r = i-(q*10) ,r直接是个位数字
r = i - ((q << 3) + (q << 1));
// 个位数字直接查找数值对应的字符,直到最后一位。
buf [--charPos] = digits [r];
i = q;
if (i == 0) break;
}
if (sign != 0) {
buf [--charPos] = sign;
}
}
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
1 parseInt(String s, int radix) 2 parseInt(String s) 3 parseUnsignedInt(String s, int radix) 4 parseUnsignedInt(String s)
2 和 4,主要是默认进制是 10,分别调用的 1 和 3
解析 parseInt(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;
// i的作用,是依次递增查找字符串上的数字
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);
// 不能只是一个 "+" or "-"
if (len == 1)
throw NumberFormatException.forInputString(s);
i++;
}
multmin = limit / radix;
// 思路是,从字符串的第一位开始取值,每次乘以进制,在加上当前位置的数字。
// 例如 "12535", 10进制 , 第一次,初始值是result=0, 0*进制10,减去第一位1,得到result为-1,第二次,初始值是result=-1,-1*进制10,减去第二位数字2,得到-12,后面,同理。其中有一些异常判断。
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;
}
-
String 转无符号 int
public static int parseUnsignedInt(String s, int radix) public static int parseUnsignedInt(String s)
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 {
// int 最大值采用最大进制表示,有5位数字,用10进制表示有10位数字
if (len <= 5 ||
(radix == 10 && len <= 9) ) {
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);
}
}
疑问:为什么要采用Long的转换方法,本身的parseInt,解析超出范围的数字也会抛异常吧?
-
创建 Integer 对象:
public static Integer valueOf(String s, int radix) public static Integer valueOf(String s) public static Integer valueOf(int i)
String 类型参数,会调用 parseInt 方法转为 int,再创建 Integer 对象,如果数字在缓存内,则从缓存取。
(8)继承 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;
}
(9)hashCode、equals
@Override
public int hashCode() {
return Integer.hashCode(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;
}
(10)getInteger 系列方法
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 {
// 若返回的系统value不是可decode的字符串,就抛出NumberFormatException
// 例如:System.getProperty("sun.arch.data.model")
// 而System.getProperty("java.version"),则报错
// System.getProperties().list(System.out);这个语句可以打印所有系统属性可取的key
v = System.getProperty(nm);
} catch (IllegalArgumentException | NullPointerException e) {
}
if (v != null) {
try {
return Integer.decode(v);
} catch (NumberFormatException e) {
}
}
return val;
}
-
decode 方法
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) {
// int 最小值在这里处理。
String constant = negative ? ("-" + nm.substring(index))
: nm.substring(index);
result = Integer.valueOf(constant, radix);
}
return result;
}
从字符串中推测出正负号、进制,并截取实际数字位,使用 valueOf
转为 int 数字,最终添加符号位,并返回。
(12)compare 系列方法
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);
}
// 1.8新增
public static int compareUnsigned(int x, int y) {
return compare(x + MIN_VALUE, y + MIN_VALUE);
}
(13)1.8 新增运算
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));
}
(14)highestOneBit、lowestOneBit
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);
}
public static int lowestOneBit(int i) {
// HD, Section 2-1
return i & -i;
}
(15)numberOfLeadingZeros、numberOfTrailingZeros
// 参考:https://www.jianshu.com/p/2c1be41f6e59
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;
}
// https://blog.csdn.net/tina_tian1/article/details/78364795
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);
}
// https://blog.csdn.net/cor_twi/article/details/53720640
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;
}
// https://blog.csdn.net/zuoyouzouzou/article/details/88892198
public static int rotateLeft(int i, int distance) {
return (i << distance) | (i >>> -distance);
}
// https://blog.csdn.net/zuoyouzouzou/article/details/88892198
public static int rotateRight(int i, int distance) {
return (i >>> distance) | (i << -distance);
}
//
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;
}
// https://www.nhooo.com/note/qa0zb9.html
public static int signum(int i) {
// HD, Section 2-7
return (i >> 31) | (-i >>> 31);
}
public static int reverseBytes(int i) {
return ((i >>> 24) ) |
((i >> 8) & 0xFF00) |
((i << 8) & 0xFF0000) |
((i << 24));
}
(15)运算
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);
}
注意点:
-
缓存问题
通过构造器创建的 Integer 对象,使用==,不会取缓存中的值,只有通过静态方法获取的 Integer 对象,在缓存范围内适用 ==。
Integer q1 = new Integer(111); Integer q2 = new Integer(111); System.out.println(q1 == q2);// false
-
核心功能,创建 Integer 对象,转字符串对象,运算,不常用的一些操作方法。