我在一项目中要用到 大量的元素交换,于是必须写一个交换两个元素的swap函数,众所周知,Java中的基本元素是不支持传址的,必须是对象或数组才能传址(引用),我开始也走了很多弯路,开始用自带的Integer包装类,发现不行。
后来自己封装了一个类能成功交换了。
class intObject
{
int value;
intObject(){}
intObject(int pV){
value=pV;
}
public void setValue(int pV){
value=pV;
}
public int getValue(){
return value;
}
};
public class Swap
{
public static void swap(intObject a,intObject b){
int temp;
temp=a.value;
a.setValue(b.getValue());
b.setValue(temp);
}
public static void main(String[] args)
{
intObject a=new intObject(3),
b=new intObject(5);
swap(a,b);
System.out.println(a.value);
System.out.println(b.value);
}
}
5
3
后来又想用数组试试看:
public class Swap
{
public static void swap(int[] a,int[] b){
a[0]^=b[0];
b[0]^=a[0];
a[0]^=b[0];
}
public static void main(String[] args)
{
int a[]={3},b[]={5};
System.out.println("before swap:");
System.out.print(""+a[0]+'/t');
System.out.println(b[0]);
swap(a,b);
System.out.print(""+a[0]+'/t');
System.out.println(b[0]);
}
}
before swap:
3 5
5 3
呵呵,也行
但要注意一点的是,在代码中调用后须把交换后的值赋回去,例如:
.....
int a[]={pA[j]},
b[]={pA[j+1]};
swap(a,b);
pA[j]=a[0];
pA[j+1]=b[0];
......
可能这样还不如直接在代码中写交换代码简洁,但这里只说明这样一种方法