互换值

方法1:

代码
public class Change {
public static void change(int x,int y) {
System.out.println(
"改变之前");
System.out.println(
"x = "+x);
System.out.println(
"y = "+y);
int z;
z
= x;
x
= y;
y
= z;
System.out.println(
"改变之后");
System.out.println(
"x = "+x);
System.out.println(
"y = "+y);
}
public static void main(String[] args) {
change(
3,4);
}
}

方法2:

对于基本数据类型传递的是数据的拷贝,而对于引用数据类型传递的是引用的拷贝。

代码
// 此类不像方法1那样是用一个临时变量来保存
public class Change {
public static void change(int x,int y) {
x
= x + y;
y
= x - y;
x
= x - y;
}

public static void change(int[] num) {
num[
0] = num[0] + num[1];
num[
1] = num[0] - num[1];
num[
0] = num[0] - num[1];
}

public static void change(Point pt) {
pt.x
= pt.x + pt.y;
pt.y
= pt.x - pt.y;
pt.x
= pt.x - pt.y;
}

public static void main(String[] args) {
int x = 3;
int y = 4;
change(x,y);
System.out.println(
"x = " + x);
System.out.println(
"y = " + y);
System.out.println();

int[] num = {3,4};
change(num);
System.out.println(
"x = " + num[0]);
System.out.println(
"y = " + num[1]);
System.out.println();

Point pt
= new Point();
pt.x
= 3;
pt.y
= 4;
change(pt);
System.out.println(
"x = " + pt.x);
System.out.println(
"y = " + pt.y);
}
}

class Point {
int x,y;
}

 

posted @ 2010-12-22 13:28  meng72ndsc  阅读(195)  评论(0编辑  收藏  举报