public final class Integer
extends Number
implements Comparable<Integer>
{}
类定义:
Integer继承自Number类,实现了Comparable<Integer>接口
Number:他是一个抽象类,拥有4个抽象方法和3个实体方法,继承了Serializable,可序列化
Comparable:实现compareTo(Integer i) 比较
类属性:
//定义Int能表示的最小值的常量 MIN_VALUE = -(2^31)
public static final int MIN_VALUE = 0x80000000;
//定义Int能表示的最大值的常量 MAX_VALUE = (2^31)-1
public static final int MAX_VALUE = 0x7fffffff;
//获取一个int 的 Class 对象实例 TYPE
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中的value[]相同,此value值为Integer对象的实际值
private final int value;
//位数为32位
public static final int SIZE = 32;
//字节数 = 32/8 = 4个字节
public static final int BYTES = SIZE / Byte.SIZE;
MIN_VALUE = 0x80000000 和 MAX_VALUE = 0x7fff ffff 因为是有符号的,所以范围是 -2147483648 ~ 2147483647
构造方法:
/**
诸如Integer number = new Integer(20);
则直接将int类型20传入给value
*/
public Integer(int value) {
this.value = value;
}
/**
调用parseInt(),将数字字符串转换为整数
*/
public Integer(String s) throws NumberFormatException {
this.value = parseInt(s, 10);
}
内部类:IntegerCache
/**
IntegerCache 提供了缓存
避免重复创建对象带来性能损耗
该值缓存范围在-128 ~ 127之间
*/
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;//给定上限为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;
//创建127-(-128)+1大小数组
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() {}
}
举例测试一下缓存范围:
如valueOf()方法就使用了缓存,如果范围不是在-128 ~ 127,则会new一个新对象
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
类方法:
看一下Integer一些常用方法的实现
//比较下值相同则相同
public boolean equals(Object obj) {
if (obj instanceof Integer) {
return value == ((Integer)obj).intValue();
}
return false;
}
//数字按照指定进制,转字符串输出
public static String toString(int i, int radix) {
//范围是<1 或者>36进制,按10进制处理
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);
最多位数为32位(也就是2进制位数最多)
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);
}
//将指定进制整数字符串转 10进制int整数
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;
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;
}
由于继承了抽象类Number,于是有方法实现
//将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;
}
int类型哈希值仍为自己
//数字的哈希code仍为原数字
public static int hashCode(int value) {
return value;
}
compare比较
/**
返回 小于、等于、大于 结果为 -1 0 1
*/
public static int compare(int x, int y) {
return (x < y) ? -1 : ((x == y) ? 0 : 1);
}
发现一个有趣的方法,求一个整数中二进制位为1的个数和,追求极致性能全是位运算,逻辑不是很好理解,感兴趣的同学可以移步 bitCount算法解读
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;
}