JAVA和C++ 交换两个变量的值的函数 区别

4 篇文章 0 订阅

在程序开发的过程,要交换两个变量的内容,是一种比较常见的事情。在排序算法中,就有一种就叫做“交换排序法”。在所有的排序算法,交换要排序的集合中的两个元素,几乎是必须的过程。在Java中交换两个元素的内容,如果你是程序员新手,你可能碰到意想不到的问题。

众所周知,java和C、C++中都不能通过值传递的方式实现两个整数的交换。

即下面的函数是不能成功交换两个整数的,


 public void swap1(int a,int b){ //值参数传递不能实现交换两个整数
  int t;
  t = a;
  a = b;
  b = t;
  
  
 }

 

在C++,可以通过引用或者指针来实现两个整数的交换,实质上是通过地址传递来实现两个整数的交换的。

void swap2(int &a,int &b)//引用传递 
{
 int temp;
 temp = a;
 a = b;
 b = temp;
}

 

还可以通过指针来实现两个整数的交换

void swap2(int *a,int *b)//指针,地址传递 
{
 int temp;
 temp = *a;
 *a = *b;
* b = temp;
}

 

那么java中又是如何实现两个整数的交换呢?

 

方法1:

通过数组方式交换:

如果一定要通过一个   method   来实现,下面的形式也许可以: 

void   swap(int[]   a)   { 
        if   (a   ==   null   ||   a.length   !=   2) 
                throw   new   IllegalArgumentException(); 
        int   temp   =   a[0]; 
        a[0]   =   a[1]; 
        a[1]   =   temp; 


代码实例如下:

//SwapInteger.java

[java]  view plain copy
  1. //实现个整数的交换  
  2.   
  3.   
  4. public class SwapInteger {  
  5. public static void swap(int a[]){      
  6. //数组传递实现交换两个整数  
  7.     int t;  
  8.     t = a[0];  
  9.     a[0] = a[1];  
  10.     a[1] = t;  
  11.            
  12.           
  13.     }  
  14. public static void main(String args[]){  
  15.      
  16.      int []a = new int[2];  
  17.      a[0] = 3;  
  18.      a[1] = 4;  
  19.      swap(a);  
  20.      System.out.println(a[0] + "/t" + a[1]);  
  21. }  
  22.   
  23. }  

 

 

2)方法2:

构造对象,将a,b作为对象的属性,然后操作对象,最后获得对应的属性。

 

class Swaper    
{    
    Swaper(int x, int y)    
    {     
        this.x = x;    
        this.y = y;    
    }    
    public Swaper swap()    
    {   
        return new Swaper(this.y, this.x);  
    }   
    public int getX() {  
        return this.x;  
    }  
    public int getY() {  
        return this.y;  
    }  
    private int x;    
    private int y;  
}   


public class TestSwaper   
{    
    public static void main(String[] args)    
    {    
        int x = 15;    
        int y = 16;    
        System.out.println("x: " + x + ", y: " + y);    
     
        Swaper swaper = new Swaper(x, y);       
        x = swaper.swap().getX();    
        y = swaper.swap().getY();    
     
        System.out.println("x: " + x + ", y: " + y);    
    }    
}   

  





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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值