交换两个int在c++中可以写:
void swap(int* x, int* y)
{ int temp;
  temp=*x;
  *x=*y;
  *y=temp;}
但java中没有引用和指针,要完成同样的功能应该怎样写呢?

解决方案 »

  1.   

    ???
    void swap(int x, int y)

      int temp;
      temp=x;
      x=y;
      y=temp;
    }
      

  2.   

    直接把指针去掉就可以了,就这样写。
    public void swap(int x,int y){
    int temp=null;
    temp=x;
    x=y;
    y=temp;
    }
      

  3.   

    汗,写form文件写习惯了,见什么后面都加null;
      

  4.   

    swap  一定要用指针??!??  who说的....CPP中也不要吧
      

  5.   

    java中基本数值类型不是值传递吗?
      

  6.   

    JAVA中间所有变量都是引用,这样讲你明白了吗
      

  7.   

    你说的不错....参数传递中...基本类型是值传递但是这里
    temp=x;
    x=y;
    y=temp;是直接赋值啊....
      

  8.   

    JAVA 中变量就是引用...通过改变引用改变形参..你说实参有无变化...既然你想弄明白...干嘛不自己写个function来验证下自己的想法
      

  9.   

    你直接按LSde 朋友的方法写  自己跟一下就很清楚了
      

  10.   

    public class SwapTip 
    {
        public static void main(String []args)
        {
           int a = 1;
           int b = 2;        System.out.println("a: " + a);
            System.out.println("b: " + b);        swap(a, b);        System.out.println("Swapped!");
            System.out.println("a: " + a);
            System.out.println("b: " + b);
        }    public static void swap(int a, int b) 
    {
            int temp;
            temp = a;
    a = b;
    b = temp;
        }
    }运行结果
    a:1
    b:2
    Swapped!
    a:1
    b:2怎么改变了?
      

  11.   

    哦...我没看清楚问题..
    这涉及的是JAVA中值传递的问题....由于基本类型是值传递...直接swap不可以
    要么用INT数组传递引用...要不通过外部内联的方式
    public class Test {
    public static void main(String[] args) {

    Test t = new Test(1,2);

    System.out.println("i: " + t.i);
    System.out.println("j: " + t.j); t.swap(); System.out.println("Swapped!");
    System.out.println("i: " + t.i);
    System.out.println("j: " + t.j);
    }
    int i,j;

    public Test(int i,int j){
    this.i = i;
    this.j = j;
    }
    public void swap() {
    int temp;
    temp = i;
    i = j;
    j = temp;
    }
    }