public class TestSwap
{
public static void main(String[] args) 
{
Integer a = new Integer(5);
Integer b = new Integer(10);
swap(a, b);
System.out.println(a + "\t" + b);
int c = 5;
int d = 10;
swap(c, d);
System.out.println(a + "\t" + b);
} public static void swap(Object a, Object b)
{
Object tmp = a;
a = b;
b = tmp;
} public static void swap(int a, int b)
{
a = a + b;
b = a;
a = a - b;
}
}我想实现交换函数,但是这样是不行的。我现在也知道为什么不行,因为传入的都是副本,第一个是Object对象句柄的副本,第二个是int的副本。但是如何才能实现交换呢?

解决方案 »

  1.   

    public class TestSwap
    {
    public static void main(String[] args) 
    {
    Integer a = new Integer(5);
    Integer b = new Integer(10);
    swap(a, b);
    System.out.println(a + "\t" + b);
    int c = 5;
    int d = 10;
    swap(c, d);
    System.out.println(a + "\t" + b);
    } public static void swap(Object a, Object b)
    {
    Object tmp = a;
    a = b;
    b = tmp;
                      this.a=a;
                      this.b=b;
    } public static void swap(int a, int b)
    {
    a = a + b;
    b = a;
    a = a - b;
                      this.a=a;
                      this.b=b;
    }
    }试试
      

  2.   

    this.a和this.b??
    怎么可能啊?编译肯定都通不过的。我在类中又没有定义a和b,哪来的this.a和this.b?
      

  3.   

    java 不像C支持指针...你这个问题,好可以用static来解决.但如你的a,b是静态的..就可以解决了.
    自己去试试..我不敢确定能否通得过,我也是菜鸟一个.呵呵.....看楼下的怎么说.
      

  4.   

    public static void swap(Integer a, Integer b)
    public static void swap(int a, int b)
    这样声明的两个函数都是实现不了交换的,因为交换了也都带不出来,你可以自己实现一个和Integer差不多的类
    比如说
    class Int{
      int value=0;
      public Int(int value){
        this.value = value;
      }  public void setValue(int value){
        this.value = value;
      }
      
      public int getValue(){
        return value;
      }
    }再象下面这样就可以实现交换
    public static void swap(Int a, Int b){
      int c = a.getValue();
      a.setValue(b.getValue());
      b.setValue(c);
    }
      

  5.   

    将欲交换的数作为一类的属性,然后在swap方法中改变之
    晕,楼上说了
    或者将欲交换的数fill进Collection,然后改变
    public static void swap(int[] s)
    {
    int temp;
    temp=s[0];
    s[0]=s[1];
    s[1]=temp;

    }                  int[] t= {5,10};
    swap(t);
    System.out.println("a="+t[0]+"\tb="+t[1]);
      

  6.   

    你们说的这些我都知道,我只是想知道能不能有种方法能够不通过封装就能够实现交换。
    不知道有没有这种方法呢?
    不然的话这也算JAVA的一点不足了吧,至少算是一种不方便吧。
      

  7.   

    那就不要写在方法里交换,直接
    Object tmp = a;
    a = b;
    b = tmp;
    可以吗