private final int value;1.继承体系
public final class Integer extends Number implements Comparable{
实现了Comparable接口,重写了CompareTo方法
public int compareTo(Integer anotherInteger) {
return compare(this.value, anotherInteger.value);
}
2.构造方法
Integer中的构造方法有两个,但均已过时,不建议使用,代替他们的是valueOf方法
public Integer(int value) {
this.value = value;
}
public Integer(String s) throws NumberFormatException {
this.value = parseInt(s, 10); //将字符串转成int型后赋值给value;
}
3.valueOf
valueOf方法有三个重载,用于替代构造方法使用,参数可以是数字型的字符串或者int数据
如果是字符串,则会调用parseInt方法将指定进制的字符串(不指定则为10进制)转换成对应的int数据,然后调用一个int型参数的valueOf方法返回对应的Integer对象,这里涉及到Interger的缓存问题,在下面讲解。
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) { //如果i在-128到127范围内,返回cache缓存里面对应的Integer数据
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i); //否则直接返回一个新对象
}
4.Integer的缓存
private static class IntegerCache {
static final int low = -128;
static final int high;
static final Integer cache[];//cache这个数组里面存放-128-127的integer数据
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];//声明一个长度为256的Integer数组
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() {}
}
测试代码
Integer i1=new Integer(100); Integer i2=new Integer(100); //构造方法每次返回一个新的Integer对象 System.out.println(i1==i2);//false Integer i3= Integer.valueOf(100);//valueOf方法如果在-128到127之内,会从缓存取出Interger对象返回 Integer i4= Integer.valueOf(100); System.out.println(i3==i4);//true System.out.println(i1==i3);//false Integer i5= Integer.valueOf(128);//valueOf方法如果不在-128-127之内,返回新的对象 Integer i6= Integer.valueOf(128); System.out.println(i5==i6);//false5.parseInt和toBinaryString
parseInt(String s,int radix); //将对应进制的数据的字符串形式转化成int类型,如果s的进制与radix不符,则抛出NumberFormatException
parseInt(String s); //不传进制,默认为10进制
toBinaryString(int i); //将i转成2进制字符串(补码)返回
代码:
int res1=Integer.parseInt("00001111",2);
int res2=Integer.parseInt("10001111",2);//如果传入的2进制位数不够32位(int)高位自动补0,所以这里符号位是0,结果为正数
String str1=Integer.toBinaryString(-143);//返回i的二进制补码字符串
System.out.println(res1);
System.out.println(res2);
System.out.println(str1);
运行结果:



