整形是基础数据类型的一种,int也有自己的包装类Integer.但是如何比较两个整形呢.
public static void main(String[] args) { Integer a = 1; Integer b = 1; int c = 1; Integer a1 = 256; Integer b1 = 256; int c1 = 256; System.out.println(a == b); System.out.println(a == c); System.out.println(b == c); System.out.println(a1.equals(b1)); System.out.println(a1 == b1); System.out.println(a1 == c1); System.out.println(b1 == c1); }
输出
true
true
true
true
false
true
true
这是因为 对于-127-128的整形,在创建包装类的时候会直接从缓存好的IntegerCache中取,所以此时用 == 会为true,但是超过这个范围就会false.
但是包装类和int比较的时候,会自动拆箱,只会比较数字.
还有一个比较火的题,这里就要用反射去改变值了.可以参考下https://www.jianshu.com/p/0f8fa37b13bd
//要求写一个swap方法交换ab值输出打印a=2 b=1
public static void main(String[] args) {
Integer a=1,b=2;
swap(a,b);
System.out.println("a="+a+" b="+b);
}
private static void swap1(Integer aa, Integer bb) {
try {
Field aaValue = aa.getClass().getDeclaredField("value");
aaValue.setAccessible(true);
aaValue.set(aa,2);
Field bbValue = bb.getClass().getDeclaredField("value");
bbValue.setAccessible(true);
//这里的1不会自动装箱,当然就不会从缓存中去取值
bbValue.set(bb,new Integer(1));
} catch (Exception e) {
e.printStackTrace();
}