int
int是基本类型的一种
== 对于基本类型比较的是值
Integer
Integer是引用类型的一种,是int类型的包装类
== 对于引用类型比较的是内存地址
int 与 Integer 的比较
Integer i = 50;
底层调用了Integer的valueOf方法
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
对于值在-128到127之间的同一个数值放入一个缓存中,不会创建新的对象
Integer c = 5;
System.out.println("c: " + System.identityHashCode(c));
Integer d = 5;
System.out.println("d: " + System.identityHashCode(d));
System.out.println(c == d);
对于同一个数值的自动装箱,对象地址是一致的
对于同一个数值创建对象,其地址是不一致的
Integer a = new Integer(5);
System.out.println("a: " + System.identityHashCode(a));
Integer b = new Integer(5);
System.out.println("b: " + System.identityHashCode(b));
System.out.println(a == b);
对于new Integer(5),底层创建了新的对象,对象的值为5
public final class Integer extends Number implements Comparable<Integer> {
private final int value;
public Integer(int value) {
this.value = value;
}
对于值在128及以上的Integer对象,都是重新创建的对象;值相同,内存一定不同
Integer e = 128;
System.out.println("e: " + System.identityHashCode(e));
Integer f = 128;
System.out.println("f: " + System.identityHashCode(f));
System.out.println(e == f);
大于128的Integer对象和相同值的int对象的比较
两者的id值显然是不等的,但是与int类型比较时默认比较的是值
Integer f = 128;
System.out.println("f: " + System.identityHashCode(f));
int g = 128;
System.out.println("g: " + System.identityHashCode(g));
System.out.println(g == f);
Integer对象之间的==操作比较的是内存地址
Integer对象之间的"<",">"等运算符操作,会将Integer先转为int再运算
转载请注明原文地址:https://ipadbbs.8miu.com/read-57222.html