java没有c#的ref,那怎么实现引用传递?即,有什么和ref等效的东西吗?
简单的例子:public static void main(String[] args)
{
  ....
  int x = 1, y = 2;
  swap(x, y);
  System.out.println("x = " + x + ", y = " + y);
  ....
}//互换两个数
static void swap(int x, int y)
{
  x = x + y;
  y = x - y;
  x = x - y;
}  怎么实现互换x y的值?谢谢指教!

解决方案 »

  1.   

    static void swap(int x, int y)
    {
      int empty;
      empty = x;
      x = y;
      y = empty;
    }  另外定义个参数,实现交换不就得了 
      

  2.   

    java中不能实现这种操作,只能变通实现
      

  3.   

    可以用c++的思维认为java中除了基本类型(byte,short,char,int,long,double,float,boolean),其他的参数传递都是指针
      

  4.   

    这样回答的都误解你的意思了,没懂ref是嘛意思。。
    不是所有搞java的都知道的
      

  5.   

    数组类型也不行啊。例子: public static void main(String[] args)
    {
      int[] a = {1,2,3,4,5};
      System.out.println(a[0]);///调用前
      swap(a[0]);
      System.out.println(a[0]);//调用后
    } //互换两个数
    static void swap(int i)
    {
    i++;
    }  
    输出结构都是1
      

  6.   

    这是把a[0]的值复制给了i,当然不行
     //互换两个数
        static void swap(int[] ar)
        {
            ar[0]++;
        }  
      

  7.   

    你的swap参数是int,是基本类型,会直接复制值给形参的
      

  8.   


    下面的代码可以了,但是换个数都这么麻烦?有没有简单点的方法? public static void main(String[] args)
    {
      int x = 1,y = 2;
      int[] a = {x,y};
      System.out.println(x + " " + y);///调用前
      swap(a);
      x = a[0];
      y = a[1];
      System.out.println(x + " " + y);//调用后
    } //互换两个数
    static void swap(int[] a)
    {
    int t = a[0];
    a[0] = a[1];
    a[1] = t;

      

  9.   

    这,很麻烦么?为什么交换一个数还要调用一个方法
    public static void main(String[] args) {
    int y = 5;
    int x = 9;
    y = (x^= (y^= x))^ y ;
    System.out.println(x);
    System.out.println(y);
    }
      

  10.   

    这样不是可以吗
    public static void main(String[] args) {
    int[] intArray = {1,2};
    test(intArray);
    System.out.println(intArray[0]+"-"+intArray[1]);
    } public static void test(int[] intArray) {
    intArray[0] = intArray[0] + intArray[1];
    intArray[1] = intArray[0] - intArray[1];
    intArray[0] = intArray[0] - intArray[1];
    }
      

  11.   

    感觉大家考虑得太复杂了哈,想简单点不是好点么?
    Java实现址传递用的是对象,既然int和Integer都不行那自己封装个不就行了:public class Test15 {
    public static void main(String[] args) {
    Int x = new Int(1), y = new Int(2);
    swap(x, y);
    System.out.println("x = " + x + ", y = " + y);
    } // 互换两个数
    static void swap(Int x, Int y) {
    x.value = (y.value ^= (x.value ^= y.value)) ^ x.value;
    }
    }class Int {
    public int value; public Int() {
    value = 0;
    } public Int(int value) {
    this.value = value;
    } @Override
    public String toString() {
    return (Integer.toString(value));
    }
    }
      

  12.   


    String 也属于引用传递是吧?
    以下代码体现只传递值,怎么可以像数组体现区别来?public class Test3 {
    public static void main(String args[]){
    String s = "hello";
    Test3 t3 = new Test3();
    t3.change(s);
    System.out.println(s);
    }

    public void change(String s){
    s = "www";
    }}