一.简介
1.Integer和Long的联系与区别
2.源代码中的享元模式
3.常用的方法
二.Integer和Long的联系与区别
相同点: Ingeter和Long都是包装类,初值为null;
通过equals比较变量是否相同,==在一定的范围内可以使用(在以下享元模式中解释);
区别:Integer是int的封装类型是整数范围-2^31到2^31-1,long 的整数范围:-2^63 ~ 2^63 -1 long是长整型;
三.源代码中的享元模式
例子
Integer i=10;
Integer j=10;
System.out.println(i==j);
//这里输出是true
Integer a=200;
Integer b=200;
System.out.println(a==b);
//这里输出是false
答案很简单==判断的是两个变量引用的地址,Integer/Long源代码在设计中缓存了-128到127之间的值,所以在这个范围内的数值都是指向同一个地址;
源代码:
缓存的实现:
//是Integer内部的私有静态内部类,里面的cache[]就是jdk事先缓存的Integer。
private static class IntegerCache {
static final int low = -128;//区间的最低值
static final int high;//区间的最高值,后面默认赋值为127,也可以用户手动设置虚拟机参数
static final Integer cache[]; //缓存数组
static {
// high value may be configured by property
int h = 127;
//这里可以在运行时设置虚拟机参数来确定h :-Djava.lang.Integer.IntegerCache.high=250
String integerCacheHighPropValue =
sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
if (integerCacheHighPropValue != null) {//用户设置了
int i = parseInt(integerCacheHighPropValue);
i = Math.max(i, 127);//虽然设置了但是还是不能小于127
// 也不能超过最大值
h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
}
high = h;
cache = new Integer[(high - low) + 1];
int j = low;
//循环将区间的数赋值给cache[]数组
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
}
private IntegerCache() {}
}
这就是就是用一个Integer数组先缓存了-128到127区间值,后面如果是是在区间内的数直接从缓存数组中取,否则才构造新的Integer。
Integer赋值时:
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];//在缓存数组区间内返回缓存中的数据
return new Integer(i);//不再区间内new一个对象
}
四.常用的方法
1.类声明和变量
public final class Integer extends Number implements Comparable<Integer> {
final类不能被继承,继承了abstract类Number,实现了抽象方法有
intValue()、longValue()、floatValue()、doubleValue()、byteValue() 、shortValue()
实现Comparable接口用于比较两个变量大小,实现方法 compareTo(T o);
private final int value;//final证明不可变性 private static final long serialVersionUID = 1360826667806852920L;
从对象不可变知道以下i生成了两个对象
public static void main(String[] args) { Integer i = new Integer(6); i = 7; }
编译后的代码是
public static void main(String args[]) { Integer i = new Integer(6); i = Integer.valueOf(7);//生成对象或者从缓存中取数据 }
2.compareTo
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,大于返回1等于返回0
}
3. 类型Value以shortValue为例子,都是通过强转
public short shortValue() {
return (short)value;
}
4. equals
private final int value;//成员变量,Integer 的值
public boolean equals(Object obj) {
if (obj instanceof Integer) {
return value == ((Integer)obj).intValue();//转化成int基础类型再做比较,所以包装类采用//equals方法进行比较大小
}
return false;
}
就先写到这里了,以下是在资料整理时看到的一篇很详细的源代码解析:
https://www.cnblogs.com/vinozly/p/5173477.html