先看一段代码
类加载器Integer时加载 IntegerCache源码
package com.lang;
/**
* @author wangyl-910
* @description
* @date 2017/11/4
* @see
*/
public class Integer {
public static void main(String[] args) {
java.lang.Integer a = 10;
java.lang.Integer b = 10;
java.lang.Integer c = 128;
java.lang.Integer d = 128;
int e = 128;
//print true
System.out.println(a==b);
//print false
System.out.println(c==d);
//print ture
System.out.println(c==e);
}
}
a==b打印true,c==b打印false
a ==b 操作时jdk会做自动装箱操作,即调用Integer.valueof方法后通过==比较,valueOf会对-128 至127的数字做缓存
所以a==b比较的是同一个对像,而c,d是两个不同的对象==时返回false
c==e jvm对c做了拆箱操作 其实是c.intvalue==e它们比较的是值所有打印true
代码如下:
Integer.valueOf源码
/**
* Returns an {@code Integer} instance representing the specified
* {@code int} value. If a new {@code Integer} instance is not
* required, this method should generally be used in preference to
* the constructor {@link #Integer(int)}, as this method is likely
* to yield significantly better space and time performance by
* caching frequently requested values.
*
* This method will always cache values in the range -128 to 127,
* inclusive, and may cache other values outside of this range.
*
* @param i an {@code int} value.
* @return an {@code Integer} instance representing {@code i}.
* @since 1.5
*/
public static Integer valueOf(int i) {
assert IntegerCache.high >= 127;
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
类加载器Integer时加载 IntegerCache源码
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;
String integerCacheHighPropValue =
sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
if (integerCacheHighPropValue != null) {
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);
}
high = h;
cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
}
private IntegerCache() {}
}
==与equals的区别
== 一般用于基本类型比较,==比较对象类型时比较的是引用
equals 用于比较对象类型,Integer,String之类的对像类型都有重写Object方法的equals方法
Integer.equals 源码
/**
* Compares this object to the specified object. The result is
* {@code true} if and only if the argument is not
* {@code null} and is an {@code Integer} object that
* contains the same {@code int} value as this object.
*
* @param obj the object to compare with.
* @return {@code true} if the objects are the same;
* {@code false} otherwise.
*/
public boolean equals(Object obj) {
if (obj instanceof Integer) {
return value == ((Integer)obj).intValue();
}
return false;
}
总结:
基本类型 ==比较值是否相等
对像类型 ==比较是否同一对象,equals比较值是否相等
备注:源码来自JDK1.7