日期:2014-05-20  浏览次数:20662 次

java中交换两个数的值
现有一个方法
public void swap(int x,inty)
在main方法中调用
swap(a,b);//a、b均为int型
调用完之后要求交换两个数的值
我们知道,这个在C/C++是十分简单的函数,但在java中该如何实现呢? 
------解决方案--------------------
public static double x,y; 
 public static void main(String[] args) 

  x = 3.0; 
  y = 4.0; 
  swap(x,y); 
  System.out.print(x+" "+y); 
 } 
  public void swap(int a,int b)
 
 { 
   x=b; 
   y=a; 
  } 

------解决方案--------------------


package com.csdn;
public class Test01 {

static int a=3;
static int b=4;
public static void main(String[] args) {

    sawp(a,b);
    System.out.println("a="+a);
    System.out.println("b="+b);


}
public static void sawp(int x,int y){
a=y;
b=x;
}

}



用函数 java交换不了
------解决方案--------------------

import java.util.concurrent.atomic.*;
public class Main{
static void swap(AtomicReference<Integer> a, AtomicReference<Integer> b) {
    Integer c = a.get();
    a.set(b.get());
    b.set(c);
}
public static void main(String[] args) {
    AtomicReference<Integer> a = new AtomicReference<Integer>(28);
    AtomicReference<Integer> b = new AtomicReference<Integer>(30);
    System.out.println("a = " + a);
    System.out.println("b = " + b);
    swap(a, b);
    System.out.println("a = " + a);
    System.out.println("b = " + b);
}
}

a = 28
b = 30
a = 30
b = 28