背景
在我们编写基础数据类型的时候有时候在做一些基础的判断的时候会发现,为啥判断的结果不一致,比如你int a =127 当 a==127是true,但是当a=128 a==128就发现是false,所以这时候会可能会很纳闷为啥不一样?当然jdk底层很多源码是值得每一个java从业者学习。
源码
Integer
先来上一道面试或者说我们刚学习的时候经常遇到的问题,也是很多面试中屡试不爽的测试~
/**
* @author: csh
* @Date: 2022/5/21 23:59
* @Description:Integer测试
*/
public class IntegerTest {
public static void main(String[] args) {
Integer i0 = 127;
Integer i1 = 127;
Integer i2 = 128;
Integer i3 = 128;
System.out.println(i0==i1);
System.out.println(i3==i2);
}
}
结果(如果不相信下面的结果可以复制代码自运行看看)
true
false
所以当你读源码去了解上面的原因,你真的很难清楚为什么上面的不一致,明明写法一样,127为啥成功,为啥128不成功,想当年用这个小小的考核在面试去,试过30+人,正确回答或回答清楚的不超过5个人(本人真实面过面试者~)。
那么如果你觉得有必要继续学习,接下来,如果你觉得这些太简单,请跳过谢谢~
代码位置:java.lang.Integer.IntegerCache,核心的原因,在Integer默认初始化的时候创建-128~127 作为缓存中放到cache数组中,所以我们通过127去判断的时候是直接读取缓存的值,所以是true,如果通过128,因为不在cache数组中所以读取不到,导致通过==判断的是内存地址,所以为false。明白???
private static class IntegerCache {
static final int low = -128;
static final int high;
static final Integer cache[];
static {
// 缓存最高值,可以通过属性来配置。
int h = 127;
//从jvm变量中获取配置(一般不会配置,特殊也很少~)
String integerCacheHighPropValue =
sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
//如果有值(基本都不会有~)
if (integerCacheHighPropValue != null) {
try {
//转成int
int i = parseInt(integerCacheHighPropValue);
//判断 i大于127则返回i,如果小于则直接返回127,所以这里如果配置小于127不会影响127
i = Math.max(i, 127);
// 最小配置不能超过 2^31-1次方~~太大了,这个是防溢出用的,一般是栈溢出
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)
//断言判断是不是大于等127
assert IntegerCache.high >= 127;
}
private IntegerCache() {}
}
通过配置jdk参数来实现最主值 -Djava.lang.Integer.IntegerCache.high=128
结果
true
true
从上面的结果是不是就可以从侧面证实这个参数就是配置integer初始缓冲大小的~
那么整体integer源码我们也了解了解
//继承number
public final class Integer extends Number implements Comparable<Integer> {
/**
*最小常量值 -2^31.
*
*/
@Native public static final int MIN_VALUE = 0x80000000;
/**
* 最大常量 2^31-1.
*/
@Native public static final int MAX_VALUE = 0x7fffffff;
/**
* 类型
* {@code int}.
*
* @since JDK1.1
*/
@SuppressWarnings("unchecked")
public static final Class<Integer> TYPE = (Class<Integer>) Class.getPrimitiveClass("int");
/**
* 将数据表示为字符,所有可能的字符
*/
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'
};
/**
转成string的方法
*/
public static String toString(int i, int radix) {
//如果基础大于或小于紧大最小值,基数为10
if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
radix = 10;
/* 如果基础值为10 */
if (radix == 10) {
return toString(i);
}
//创建char缓冲
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));
}
//无符号10进制转换
public static String toUnsignedString(int i, int radix) {
return Long.toUnsignedString(toUnsignedLong(i), radix);
}
//以十六进制基数 16 的无符号整数形式返回整数参数的字符串表示形式。
public static String toHexString(int i) {
return toUnsignedString0(i, 4);
}
//以十六进制基数 无符号转换反回
public static String toOctalString(int i) {
return toUnsignedString0(i, 3);
}
//将入参转成无符号二进制返回
public static String toBinaryString(int i) {
return toUnsignedString0(i, 1);
}
/**
* 无符号转换
*/
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);
}
//将整数转成指定进制的值返回
//val 传入的值
//shift 进制 十六进制为4,八进制为3,二进制为1
//buf 要写入的缓冲区数组
//offset 目标缓冲区偏移量
//len 要写入的字符长度
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 {
//将缓冲区的位置赋值为0~z的一个字符
buf[offset + --charPos] = Integer.digits[val & mask];
//右移
val >>>= shift;
} while (val != 0 && charPos > 0);
return charPos;
}
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',
} ;
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);
}
public static String toUnsignedString(int i) {
return Long.toString(toUnsignedLong(i));
}
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;
}
}
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;
}
//强转成int
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;
//如果长度大于0
if (len > 0) {
//获取第1个
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;
}
//将string转成Int
public static int parseInt(String s) throws NumberFormatException {
return parseInt(s,10);
}
//无符号将字符串转成Int
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);
}
}
//无符号将string转int
public static int parseUnsignedInt(String s) throws NumberFormatException {
return parseUnsignedInt(s, 10);
}
//将string转Int
public static Integer valueOf(String s, int radix) throws NumberFormatException {
return Integer.valueOf(parseInt(s,radix));
}
//将string转Int
public static Integer valueOf(String s) throws NumberFormatException {
return Integer.valueOf(parseInt(s, 10));
}
//intteger 初始化缓冲类,主要初始化缓冲数组 默认从 -128~127 创建放到缓冲区中
private static class IntegerCache {
//最低位
static final int low = -128;
//高位
static final int high;
//缓冲数组
static final Integer cache[];
static {
// 缓存最高值,可以通过属性来配置。
int h = 127;
//从jvm变量中获取配置(一般不会配置,特殊也很少~)
String integerCacheHighPropValue =
sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
//如果有值(基本都不会有~)
if (integerCacheHighPropValue != null) {
try {
//转成int
int i = parseInt(integerCacheHighPropValue);
//判断 i大于127则返回i,如果小于则直接返回127,所以这里如果配置小于127不会影响127
i = Math.max(i, 127);
// 最小配置不能超过 2^31-1次方~~太大了,这个是防溢出用的,一般是栈溢出
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)
//断言判断是不是大于等127
assert IntegerCache.high >= 127;
}
private 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);
}
/**
* 值
*
* @serial
*/
private final int value;
//初始化构造方法
public Integer(int value) {
this.value = value;
}
//初始化将string转成int 比如 new Integer("13")
public Integer(String s) throws NumberFormatException {
this.value = parseInt(s, 10);
}
/**
* 获取值的byte值
*/
public byte byteValue() {
return (byte)value;
}
/**
*
* 将int转成short返回
*/
public short shortValue() {
return (short)value;
}
/**
*
* 获取基础类型 int 而非integer,也即非包装类型
*/
public int intValue() {
return value;
}
/**
*
* 将integer 转成long类型返回
*/
public long longValue() {
return (long)value;
}
/**
* 将Integer转成float类型将返回;
*/
public float floatValue() {
return (float)value;
}
/**
* 将integer转成double并返回
*/
public double doubleValue() {
return (double)value;
}
/**
* 将integer值转成string并返回
*/
public String toString() {
return toString(value);
}
/**
* 获取当前值的hashCode
*/
@Override
public int hashCode() {
return Integer.hashCode(value);
}
/**
* 返回值(其实hash就是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;
}
/**
* 通过字符串获取 整形 比如:Integer.getInteger("3");
*/
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;
}
/**
* 获取字符串
*/
public static Integer decode(String nm) throws NumberFormatException {
int radix = 10;
int index = 0;
boolean negative = false;
Integer result;
//如果长度等于0 直接跑出异常
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;
}
/**
* 对比大小,如果 左值大于右值返回1 否则返回-1(需要创建实例后调用)
*/
public int compareTo(Integer anotherInteger) {
return compare(this.value, anotherInteger.value);
}
/**
* 对比大小,如果 左值大于右值返回1 否则返回-1(可以直接用Integer调用)
*/
public static int compare(int x, int y) {
return (x < y) ? -1 : ((x == y) ? 0 : 1);
}
/**
* 无符号对比,同上
*/
public static int compareUnsigned(int x, int y) {
return compare(x + MIN_VALUE, y + MIN_VALUE);
}
/**
*
* 转成log类型输出(无符号)
*/
public static long toUnsignedLong(int x) {
return ((long) x) & 0xffffffffL;
}
/**
* 转成无符除法 比如:Integer.divideUnsigned(2, 1)
*/
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));
}
/**
* 无符号取余计算 比如:Integer.remainderUnsigned(2,2)
*/
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));
}
// Bit twiddling
/**
* 二进制 32位,作为常量转换使用
*/
@Native public static final int SIZE = 32;
/**
* BYTES 为4位
*/
public static final int BYTES = SIZE / Byte.SIZE;
/**
* 二进制左边的位数全部补0 System.out.println(Integer.highestOneBit(10));
* 详细可以看这个文章:https://blog.csdn.net/jessenpan/article/details/9617749
*/
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参数i,返回其二进制最低位1的权值。
* 参考:https://blog.csdn.net/Jiapengcs/article/details/73321638?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522165340542716781483787292%2522%252C%2522scm%2522%253A%252220140713.130102334..%2522%257D&request_id=165340542716781483787292&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~sobaiduend~default-1-73321638-null-null.142^v10^pc_search_result_control_group,157^v12^control&utm_term=lowestOneBit&spm=1018.2226.3001.4187
*/
public static int lowestOneBit(int i) {
// HD, Section 2-1
return i & -i;
}
/**
*
* 参考:https://blog.csdn.net/u010667082/article/details/51819231?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522165340550916782390584162%2522%252C%2522scm%2522%253A%252220140713.130102334..%2522%257D&request_id=165340550916782390584162&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~baidu_landing_v2~default-4-51819231-null-null.142^v10^pc_search_result_control_group,157^v12^control&utm_term=numberOfLeadingZeros&spm=1018.2226.3001.4187
*/
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;
}
/**
* 获取long类型数值从高位开始连续0的个数
* 参考:https://blog.csdn.net/weixin_39935887/article/details/85267486?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522165340569316782391868467%2522%252C%2522scm%2522%253A%252220140713.130102334..%2522%257D&request_id=165340569316782391868467&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~baidu_landing_v2~default-3-85267486-null-null.142^v10^pc_search_result_control_group,157^v12^control&utm_term=numberOfTrailingZeros&spm=1018.2226.3001.4187
*/
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的数量 Integer.bitCount(10)
* 参考:https://blog.csdn.net/u011497638/article/details/77947324?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522165340576616781818793874%2522%252C%2522scm%2522%253A%252220140713.130102334..%2522%257D&request_id=165340576616781818793874&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~top_positive~default-1-77947324-null-null.142^v10^pc_search_result_control_group,157^v12^control&utm_term=bitCount&spm=1018.2226.3001.4187
*/
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/cnds123321/article/details/117362244?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522165340582316782350938275%2522%252C%2522scm%2522%253A%252220140713.130102334..%2522%257D&request_id=165340582316782350938275&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~sobaiduend~default-1-117362244-null-null.142^v10^pc_search_result_control_group,157^v12^control&utm_term=rotateLeft&spm=1018.2226.3001.4187
*/
public static int rotateLeft(int i, int distance) {
return (i << distance) | (i >>> -distance);
}
/**
* 补码二进制数右移指定位数获得的值
* 参考:https://blog.csdn.net/zuoyouzouzou/article/details/88892198?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522165340582316782350938275%2522%252C%2522scm%2522%253A%252220140713.130102334..%2522%257D&request_id=165340582316782350938275&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~sobaiduend~default-2-88892198-null-null.142^v10^pc_search_result_control_group,157^v12^control&utm_term=rotateLeft&spm=1018.2226.3001.4187
*/
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;
}
/**
*如果参数为 0,则返回 0;如果参数大于 0,则返回 1.0;如果参数小于 0,则返回 -1.0。
* 参考:https://blog.csdn.net/zl_meng/article/details/78897431?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522165340621316781435412805%2522%252C%2522scm%2522%253A%252220140713.130102334..%2522%257D&request_id=165340621316781435412805&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~sobaiduend~default-1-78897431-null-null.142^v10^pc_search_result_control_group,157^v12^control&utm_term=signum&spm=1018.2226.3001.4187
*/
public static int signum(int i) {
// HD, Section 2-7
return (i >> 31) | (-i >>> 31);
}
/**
*将一个int类型的整数的二进制位按照字节(1个字节等于8位)进行反转
* 参考:https://blog.csdn.net/cnds123321/article/details/117387242?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522165340641116781818715020%2522%252C%2522scm%2522%253A%252220140713.130102334..%2522%257D&request_id=165340641116781818715020&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~sobaiduend~default-2-117387242-null-null.142^v10^pc_search_result_control_group,157^v12^control&utm_term=integer.reversebytes&spm=1018.2226.3001.4187
*/
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);
}
}
Long的也类似 -128正的128
位置:java.lang.Long.LongCache
private static class LongCache {
private LongCache(){}
static final Long cache[] = new Long[-(-128) + 127 + 1];
static {
for(int i = 0; i < cache.length; i++)
cache[i] = new Long(i - 128);
}
}
位置:java.lang.Byte.ByteCache
private static class ByteCache {
private ByteCache(){}
static final Byte cache[] = new Byte[-(-128) + 127 + 1];
static {
for(int i = 0; i < cache.length; i++)
cache[i] = new Byte((byte)(i - 128));
}
}
位置:java.lang.Short.ShortCache
private static class ShortCache {
private ShortCache(){}
static final Short cache[] = new Short[-(-128) + 127 + 1];
static {
for(int i = 0; i < cache.length; i++)
cache[i] = new Short((short)(i - 128));
}
}
位置:java.lang.Character.CharacterCache
private static class CharacterCache {
private CharacterCache(){}
static final Character cache[] = new Character[127 + 1];
static {
for (int i = 0; i < cache.length; i++)
cache[i] = new Character((char)i);
}
}
除了Double/Float没有发现缓存其他都有~
下面呢是boolean的源码
public final class Boolean implements java.io.Serializable,
Comparable<Boolean>
{
/**
*常量true
*/
public static final Boolean TRUE = new Boolean(true);
/**
* 常量false
*/
public static final Boolean FALSE = new Boolean(false);
/**
* 表示boolean为一个类对象(jvm会通过class.c中的一个Java_java_lang_Class_getPrimitiveClass方法来获取)
*/
@SuppressWarnings("unchecked")
public static final Class<Boolean> TYPE = (Class<Boolean>) Class.getPrimitiveClass("boolean");
/**
* 初始化后不可改变
* */
private final boolean value;
/** use serialVersionUID from JDK 1.0.2 for interoperability */
private static final long serialVersionUID = -3665804199014368530L;
/**
* Boolean 构造方法
*/
public Boolean(boolean value) {
this.value = value;
}
/**
* 传入字符串强转为 布尔的构造方法
*/
public Boolean(String s) {
this(parseBoolean(s));
}
/**
* 强转方法
*/
public static boolean parseBoolean(String s) {
//判断不为空并且匹配为true
return ((s != null) && s.equalsIgnoreCase("true"));
}
/**
* 获取布尔值
*/
public boolean booleanValue() {
return value;
}
/**
* 初始化方法 jvm推荐使用 Boolean.valueof(true) 这种写法
*/
public static Boolean valueOf(boolean b) {
return (b ? TRUE : FALSE);
}
/**
* 传入字符串强转为布尔值
*/
public static Boolean valueOf(String s) {
return parseBoolean(s) ? TRUE : FALSE;
}
/**
* 将布尔转成字符串输出 true或false
*/
public static String toString(boolean b) {
return b ? "true" : "false";
}
/**
* 同上类似
*
*/
public String toString() {
return value ? "true" : "false";
}
/**
* 获以布尔的hashcode
*/
@Override
public int hashCode() {
return Boolean.hashCode(value);
}
/**
* 最原始实现,返过判断为真或假返回 1231或1237
* 所以booleanr hashcodeo 1231或 1237
*/
public static int hashCode(boolean value) {
return value ? 1231 : 1237;
}
/**
* 判断两个布尔值是否一致
*/
public boolean equals(Object obj) {
if (obj instanceof Boolean) {
return value == ((Boolean)obj).booleanValue();
}
return false;
}
/**
*通过名称获取系统初始变量布尔值
*/
public static boolean getBoolean(String name) {
boolean result = false;
try {
//强转系统变量
result = parseBoolean(System.getProperty(name));
} catch (IllegalArgumentException | NullPointerException e) {
//异常不处理
}
//如果异常返回false(有抗,如果没有配就完完了~)
return result;
}
/**
* 对比两个布尔是否一致
*/
public int compareTo(Boolean b) {
return compare(this.value, b.value);
}
/**
* 对比两个布欠的实现 如果为直返回0 否则返回 x为真返回1 假返回-1
*/
public static int compare(boolean x, boolean y) {
return (x == y) ? 0 : (x ? 1 : -1);
}
/**
* 取且的关系,如果两个都为直或假则返回直,如不一样则为false
*/
public static boolean logicalAnd(boolean a, boolean b) {
return a && b;
}
/**
* 返回取或关系,如果一个为真则返回真,两个都是假则返回假
*/
public static boolean logicalOr(boolean a, boolean b) {
return a || b;
}
/**
* 位运算
Boolean.logicalXor(true,true); //-2147483648
Boolean.logicalXor(false,true); //-1
Boolean.logicalXor(false,false); //16777216
*/
public static boolean logicalXor(boolean a, boolean b) {
return a ^ b;
}
}
最后
通过阅读源码,可以发现我们平时自已手写的大量工具其实Jdk里面已经提供,并且很多底层方法我们根本或者说很少用到,真的是一块值得我们去阅读的学习资料,并且随着深入jdk基础类型的实现,再去读其他源码会发现这些其实都挺简单的,基本的初级同学都可以看懂,唯一一些复杂我们可以借鉴一些资料学习,并且从另一方面可以学习开源大佬们的一些写代码风格真的是很值 很值~~。本文其实仅以integer全部和boolean全部其他都类似所以没有全布贴出,如果感兴趣的同学可以自行学习或联系我交流~~