关于java 交换swap的一个问题
来源:百度知道 编辑:UC知道 时间:2024/09/14 06:59:55
public class Demo2 {
static Integer c = new Integer(200);
public static void main(String []args) {
Integer a = new Integer(4);
Integer b = new Integer(100);
System.out.println("a: " + a);
System.out.println("b: " + b);
System.out.println("c: " + c);
swap(a, b);
System.out.println("Swapped!");
System.out.println("a: " + a);
System.out.println("b: " + b);
System.out.println("c: " + c);
}
public static void swap(Object o1, Object o2) {
Object t = o1;
o1 = o2;
o2 = t;
c = 10000;
}
}
我想问的是 后面输出的a b c 变了么... 为什么 谢谢
static Integer c = new Integer(200);
public static void main(String []args) {
Integer a = new Integer(4);
Integer b = new Integer(100);
System.out.println("a: " + a);
System.out.println("b: " + b);
System.out.println("c: " + c);
swap(a, b);
System.out.println("Swapped!");
System.out.println("a: " + a);
System.out.println("b: " + b);
System.out.println("c: " + c);
}
public static void swap(Object o1, Object o2) {
Object t = o1;
o1 = o2;
o2 = t;
c = 10000;
}
}
我想问的是 后面输出的a b c 变了么... 为什么 谢谢
那个swap函数唯一的作用就是改变c的值为10000。
a,b虽然使用的int的包装类Integer,但是他在函数里面使用一个指针覆盖另外一个指针的复制方法,所以对所传进函数的指针是没有任何的改变。
我想说我是学free pascal的不过勉强可以看懂一点~
所以我有限的知识告诉我输出的是
a:100
b:4
c:10000
public static void 应该相当于pascal里的procedure吧,
那么 t=o1;
o1 = o2;
o2 = t;
这段就是交换的意思噶, "t=4, a=100 b=4"这样吧, 然后c没改变过,
阿如果不是这么回事请不要睬我- -。
java 分基本数据类型和高级数据类型,基本数据类型交换的是值,高级数据类型交换的是地址,明白?Integer是高级数据类型,int是基本数据类型,所以abc的值定会变化。