Java中使用反射实现两数交换遇到的坑(二)
哈哈哈,我又来了,继上一篇的问题,继续来讨论~
主要来讨论下
java.lang.reflect.Filed.class中setInt()
与set()
的区别
直接上代码~
setInt()
代码:
//使用反射交换两个整数
private static void swap(Integer i, Integer j) {
int temp = i;
try {
Field field = i.getClass().getDeclaredField("value");
field.setAccessible(true);
field.setInt(i,j);
field.setInt(j,temp);
System.out.println(temp);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Integer i = 1;
Integer j = 2;
swap(i,j);
System.out.println("i:" + i);
System.out.println("j:" + j);
}
看过上一篇的童鞋都知道,这个是一个正确代码,可以实现交换两数~
那么我们看看下面这一段代码~
public class test {
//使用反射交换两个整数
private static void swap(Integer i, Integer j) {
int temp = i;
try {
Field field = i.getClass().getDeclaredField("value");
field.setAccessible(true);
field.set(i,j);
field.set(j,temp);
System.out.println(temp);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Integer i = 1;
Integer j = 2;
swap(i,j);
System.out.println("i:" + i);
System.out.println("j:" + j);
}
大家看出来和前面的代码有什么不一样了吗?
就是把setInt()
换成set()
,那么这两个函数有什么区别呢?
大家先猜猜结果吧~
.
.
.
.
.
.
.
.
.
.
.
和你想的答案一样吗?
有的人可能以为不能使用这个函数进行两数交换,再来看一段代码~
//使用反射交换两个整数
private static void swap(Integer i, Integer j) {
int temp = i;
try {
Field field = i.getClass().getDeclaredField("value");
field.setAccessible(true);
field.set(i,j);
field.set(j,temp);
System.out.println(temp);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Integer i = 128;
Integer j = 129;
swap(i,j);
System.out.println("i:" + i);
System.out.println("j:" + j);
}
再猜猜这个的结果是什么?
.
.
.
.
.
.
.
.
.
.
哈哈哈,是不是有点崩溃,同样的代码,换了个数,怎么就不一样了呢?
下面来解释一下~
先来看看这两个函数的源码:
是不是发现区别了,一句话总结就是,参数不同
如果你定义的第二个参数为int
类型,使用set()
函数时,他会自动装箱成Integer
类型,相反,使用setInt()
就不会进行装箱~
老规矩,画个图
① i = 1, j = 2的情况
int temp = i;
field.set(i,j);
field.set(j,temp);
大家懂了吗?
这里涉及到Integer缓存数组的问题,在[-128,127]
这个范围内,Integer会直接去找缓存数组
中有没有对象的引用,如果有,直接返回
,如果没有,也就是不在这个范围,就会新建
一个Integer对象
有些人肯定疑问,为什么temp自动装箱的临时变量,指向了i的地址,用最通俗的话将,就是,你去住酒店,你怎么来找房间,你肯定会去找你自己的房间号,而不会去找房间里的东西有没有变化~
.
.
.
.
.
.
.
.
大家懂了吗~
而不在这个范围内的数,便会在堆中开辟一个新地址,不会涉及指向同一个房间的问题~
总结
- 变量temp为
int
类型时setInt()
函数没有数范围问题set()
函数存在范围问题,[-128,127]
之间的数,不能实现两数互换,范围之外的数,可以实现两数互换~