最近我碰到一个经典问题,写一个函数Swan(a,b),要求交换a,b的值。
因为Java是不支持指针和传址,我想来想去,感觉这个函数还没法子简单的写出来了。Core Java是这么说明参数传递的原则的:
A method cannot modify a parameter of primitive type (that is, numbers or Boolean values).A method can change the state of an object parameter.A method cannot make an object parameter refer to a new object.
因为Java是不支持指针和传址,我想来想去,感觉这个函数还没法子简单的写出来了。Core Java是这么说明参数传递的原则的:
A method cannot modify a parameter of primitive type (that is, numbers or Boolean values).A method can change the state of an object parameter.A method cannot make an object parameter refer to a new object.
再说交换变量这种问题用写函数吗?!public class Swap
{
static class Swapper
{
public int i;
public int j;
public Swapper(int i, int j)
{
this.i = i;
this.j = j;
}
}
public static void main(String[] args)
{
int i = 66;
int j = 88;
Swapper temp = new Swapper(i, j);
swap(temp);
i = temp.i;
j = temp.j;
System.out.println(i + "\t" + j);
}
public static void swap(Swapper swapper)
{
swapper.i = swapper.i + swapper.j;
swapper.j = swapper.i - swapper.j;
swapper.i = swapper.i - swapper.j;
}}
在C++中,代码写得紧凑的话,交换两个变量有一行就可搞定了。
如果定义个宏就更直观了。但Java玩不了这个。
注意一下上面的代码,在main中调用swap时先new了一个Swapper对象,调用完swap后,又要对i和j分别重新赋值,有这工夫直接交换变量多好。
无论从效率还是可读性,上面的代码都是不可取的。
如果楼主只是想了解一下怎样在函数(方法)里改变参数的话,对指针和引用深入了解一下就明白了。
这个不是java的问题,在java里没有这样的函数,也不应该这样考虑问题。
public class Shu{
public static void change(int num[])
{
num[0]=num[1]+num[0];
num[1]=num[0]-num[1];
num[0]=num[0]-num[1];
System.out.println(num[0]+"**"+num[1]);
}
public static void change(int x,int y)
{
x=x+y;
y=x-y;
x=x-y;
System.out.println(x+"****"+y);
}
public static void change(Point pt)
{
pt.x=pt.x+pt.y;
pt.y=pt.x-pt.y;
pt.x=pt.x-pt.y;
System.out.println(pt.x+"*****"+pt.y);
}
public static void main(String[] args)
{
int num[]=new int[]{2,3};
change(num);
System.out.println(num[0]+"**"+num[1]);
int x=2;
int y=3;
change(x,y);
System.out.println(x+"****"+y);
Point pt=new Point();;
pt.x=3;
pt.y=4;
change(pt);
System.out.println(pt.x+"*****"+pt.y);
}
}
x=y-x;
y=y-x;
算法可以是这样的。
public class ok
{
static void swan(int a,int b)
{
int c;
c=a;
a=b;
b=c;
System.out.println("a= "+a);
System.out.println("b=" +b);
} public static void main()
{
swan(40,20); }
}
基于j2ee平台的大型电子商务网站源代码下载 :本源代码可以帮助大家了解大型物品买卖和交换网站如淘宝,易宝乐等网站的开发和创建。
下载地址: http://www.ebaole.com/sourcedown.html
并且开辟了一个社区专门为大家提供源代码的交流和讨论!
int x;
int y; void swap() {
x ^= y;
y ^= x;
x ^= y;
}
}class B {
void swap(A a) {
a.x ^= a.y;
a.y ^= a.x;
a.x ^= a.y;
}
}而不是swap(int x, int y)
对于基本类型(还有String)想交换值是不可能的
写一个linofficewhl(黑仔) 这样的程序是行的
在java中如果你传入的是基本数据类型,那么你传的就是值
如果你穿的是对象,那么你传的就是引用
我们要交换两个基本数据类型的值的话
我们可以先转化为对应的对象类型
然后传入函数