用Java交换两个元素的swap函数

我在一项目中要用到 大量的元素交换,于是必须写一个交换两个元素的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];

......

可能这样还不如直接在代码中写交换代码简洁,但这里只说明这样一种方法

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

laiwusheng

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值