1 Integer之间的比较
public class test2 {
public static void main(String[] args) {
Integer a = new Integer(1);
Integer b = new Integer(1);
//自动装箱,等价于Integer sInteger=Integer.valueOf(0),
// 当c的范围在[min,max]中间时,取缓存值
// 同时,这个缓存值不是取得上面a或者b,而是new了一个新对象放到缓存中
//因此c==a或者b都是false
Integer c = 1;
System.out.println(a==b);
System.out.println(a.equals(b));
System.out.println(a==c);
System.out.println(c.equals(b));
}
}
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);
}
2 Integer与int的比较
public class test2 {
public static void main(String[] args) {
Integer a = new Integer(1);
Integer b = 1;
//与int进行比较的时候,Integer直接会拆箱,比较值
//所以用==和equals结果是一样的
int c = 1;
System.out.println(a==c);
System.out.println(a.equals(c));
System.out.println(b==c);
System.out.println(b.equals(c));
}
}
1、引用类型之间的比较,由于存在-127至128之间的缓存对象,因此使用== 进行比较存在风险。优先使用equals进行比较
3 Long和int的比较
public class test2 {
public static void main(String[] args) {
Long b = new Long(129);
int c = 129;
System.out.println(b==c);
//c不是Long类型的,所以,直接equals直接返回false
//下面为Long的equals方法
// public boolean equals(Object obj) {
// if (obj instanceof Long) {
// return value == ((Long)obj).longValue();
// }
// return false;
// }
System.out.println(b.equals(c));
long d = 129;
System.out.println(c==d);
//向上转型:可以自动转
long e = c;
//向下转型:必须强制转换
int f= (int)d;
}
}