Java基础之Integer解析
Integer的定义
首先举例一个经典面试题知识点
public class Test {
public static void main(String[] args) {
Integer a = 100;
Integer b = 100;
int f = 100;
System.out.println(a.equals(b));//true
System.out.println(a == b);//true
System.out.println(b == f);//true
Integer c = 200;
Integer d = 200;
int e = 200;
System.out.println(c.equals(d));//true
System.out.println(c == d);//false
System.out.println(d == e);//true
Integer h = new Integer(100);
Integer i = new Integer(100);
System.out.println(h == i);//false
}
}
然后看JDK源码中类Integer的定义:
package java.lang;
import java.lang.annotation.Native;
public final class Integer extends Number implements Comparable<Integer> {
@Native private static final long serialVersionUID = 1360826667806852920L;
@SuppressWarnings("unchecked")
public static final Class<Integer> TYPE = (Class<Integer>) Class.getPrimitiveClass("int");
//最小值
@Native public static final int MIN_VALUE = 0x80000000;
//最大值
@Native public static final int MAX_VALUE = 0x7fffffff;
//值
private final int value;
//构造方法
public Integer(int value) {
this.value = value;
}
...
...
}
可以看出:
Integer是int的包装类(int是Java的八种基本数据类型之一)
Integer是一个已被序列化final类,默认值是null,是对象的引用
Integer的值在-2147483648~2147483647(21亿)之间,与int相同
Integer的方法
- Integer.SIZE
@Native public static final int SIZE = 32;
- Integer.hashCode()
//重写hashCode方法
@Override
public int hashCode() {
//value为Integer的int值
return Integer.hashCode(value);
}
- Integer.equals()
public boolean equals(Object obj) {
//如果参数同为Integer类
if (obj instanceof Integer) {
//对比int值,相等返回ture
return value == ((Integer)obj).intValue();
}
//否则返回false
return false;
}
- Integer.valueOf()
//即int装箱Integer的方法
public static Integer valueOf(int i) {
//如果int参数在缓存IntegerCache中,则直接返回该对象
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
//不在缓存中,则new一个Integer对象返回
return new Integer(i);
}
也就是说,如果是-128~127之间的数,直接从缓存获取已有对象
其中IntegerCache的实现(转自清浅池塘)