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

解决方案 »

  1.   

    这种是不借助临时变量的方法:
    public void swap(int x,inty) {x=x+y;
    y=x-y;
    x=x-y;}
    2.借助临时变量的方法
    public void swap(int x,inty) {int temp=x;
    x=y;
    y=temp;}
      

  2.   

    Java如果是作为参数传递进来的,那么实现不了这个功能
      

  3.   

    java基本数据类型作为参数 只能传值 对象只能传引用
    不像c/c++那样
    public void swap(int x,inty) 这个只不能改变x 、y的值的 一旦离开此个方法 x 、y照样是原来的值 改变不了
      

  4.   

    这种是不借助临时变量的方法:
    public void swap(int x,inty) {x=x+y;
    y=x-y;
    x=x-y;}
    2.借助临时变量的方法
    public void swap(int x,inty) {int temp=x;
    x=y;
    y=temp;}
      

  5.   

    一楼的答案是错误的。在java中,基本类型的变量是传递的值,不是传递的引用。
      

  6.   

    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; 
      } 
      

  7.   

    9楼是正解,无论值传递还是引用传递,在java中都不能实现一楼的交换
      

  8.   

    典型的算法。。以后交换都是这样算。
    int temp 
    temp = x;
    x = y;
    y = temp;
    两个书就交换了。
     
      

  9.   

    void swap(int[] data,int index1,int index2){
       int tmp = data[index1];
       data[index1] = data[index2];
       data[index2] = tmp;
    }
      

  10.   


    有那么简单吗?x、y是形参,交换之后跟a、b有何关系?
      

  11.   


    如果我定义死了swap(int x,int y)呢?现在我要交换的是两个int型的变量,不是数组里的变量,更不能传下标
      

  12.   

    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交换不了
      

  13.   

    JAVA中不是有一个swap的多态算法吗?好像还可以用Collections类的shuffle这个多态算法来实现吧。
      

  14.   

    如果你定义死了,在C+里的实现是很简单的只要传指针就可以了swap(int *i,int*j),函数必须声明成这个样子,如果用java,那只有使用对象了,因为函数中的对象参数使用的是引用,这样估计应该可以调换,自己声明的对象应该一定可以的,所以不能用int可以尝试用下Integer试试。成不成希望高手多指教。
      

  15.   

    Java中,把这两个数xy,组成数组,然后交换返回。
      

  16.   


    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
      

  17.   

    在main里调用函数的方法是不行的,交换代码直接写在main里还差不多。而且我觉得你既然用java写,就应该体现面向对象
    把这些封装成一个类比较好,x,y作为类的成员变量,再通过成员方法进行交换。。
      

  18.   


    public swap(object x,object y)
    {
      object tmp=y;
      y=x;
      x=tmp;
    }不知道这样行不行,利用int等值类型的自动装箱拆箱...
      

  19.   


    java 不是c/C++,不能这样交换的
    就算是C/C++,这样写也是交换不了的 
      

  20.   

    在 java 中要达到楼主的目的很难,当然各种特殊情况的办法也是有的,不过正因为对被交换的两个数据有特殊要求,所以就失去了一般性。比如情况一:把被交换的两个变量设置成类的静态变量
    public class Test{
        public static int a;
        public static int b;
        //......
        public void swap(){
            int tmp = a;
            a = b;
            b = tmp;
        }
    }
    但是这样写,要求变量 a 和 b 是类的静态成员变量。并且这个方法只能在 Test 类中使用,如果有类似的需求,比如 Test1 中也有两个静态成员变量,a1, b1,那么这个 swap 就只能在 Test1 类中再重写一次。
    情况二:被交换的是一个类的两个成员变量
    这种情况比前一种情况更有普遍性,但是它还是只限于类成员变量,这时可以使用反射// 定义一个交换器
    class SwapUtil{
        public static boolean swapInt(Object obj, String field1, String field2){
            try{
                Class cls = obj.getClass();
                
                java.lang.reflect.Field f1 = cls.getDeclaredField(field1);
                f1.setAccessible(true);
                 
                java.lang.reflect.Field f2 = cls.getDeclaredField(field2);
                f2.setAccessible(true);
                
                int a = f1.getInt(obj);
                int b = f2.getInt(obj);
                
                f1.setInt(obj, b);
                f2.setInt(obj, a);
                
                return true;
            }catch(Throwable ex){
                return false;
            }
        }
    }// 被设置的类 
    class TestSwaper{
        private int inta = 10;
        private int intb = 20;
        
        public void print(){
            System.out.println("inta = " + inta + ", intb = " + intb);
        }
    }
    public class Test{
        public static void main(String[] args){
            TestSwaper testObj = new TestSwaper();
            System.out.println("交换前:");
            testObj.print();
            
            boolean swapResult = SwapUtil.swapInt(testObj, "inta", "intb");
            
            System.out.println("交换" + (swapResult ? "成功" : "失败"));
            
            System.out.println("交换后:");
            testObj.print();
        }
    }这种情况的适应性更大些,并且可以交换私有成员变量,但是前提是调用时必须知道被交换的两个类成员变量的变量名
    而对于局部成员变量,除非你是把数据放到数组或者再封装到类里,否则是无法进行交换的:
    class SwapUtil{
        public static boolean swapInt(int[] array, int idx1, int idx2){
            int a, b;
            int aOK = false, bOK = false;
            try{
                int a = array[idx1];
                aOK = true;
                int b = array[idx2];
                bOK = true;
                
                int tmp = array[idx1];
                array[idx1] = array[idx2];
                array[idx2] = tmp;
            }catch(ArrayIndexOutOfBoundException ex){
                // 如果交换出现异常,则将数组数据还原
                if(aOK)
                    array[idx1] = a;
                if(bOK)
                    array[idx2] = b;
                return false;
            }
        }
    }public class Test{
        private static void printArray(int[] array){
            String pre = "";
            for(int a : array){
                System.out.println(pre + a);
                pre = ", ";
            }
        }
        public static void main(String[] args){
            int[] intArray = new int[]{1, 2, 3, 4, 5, 6, 7};
            
            System.out.println("交换前:");
            printArray(intArray);
            
            // 交换数组中的第  3,5 个元素
             SwapUtil.swapInt(intArray, 3, 5);
            
            System.out.println("交换后:");
            printArray(intArray);
        }
    }
      

  21.   

    private int x;
    private int y;public void swap(int x,int y){   this.x = y;
       this.y = x;
       
    }
      

  22.   


    办法有很多,但每种办法都对被交换的数据有一定的要求,你的这个办法里,要求被交换的是类的两个成员变量,适应性不广其实这是java语言的局限性,java 没有指针,所以无法很好地满足楼主的需求
      

  23.   

    Java中方法的参数都是值传递。 只有对象才是引用传递。
    Interger对象在值小于127时也会自动转型为基本类型。值太小也传不了可以用Stringbuffer来做引用传递(不建议使用),或者返回数组。至于方法里面,常规都是借助临时变量吧。
      

  24.   

    1.不用临时变量有两种方法
    public void swap(int a,int b) {a=a+b;
    b=a-b;
    a=a-b;}
    public void swap(int a,int b){
    a=a+b;
    b=a^b;
    a=a^b;
    }
    2.用临时变量的方法
    public void swap(int a,int b) {int temp=a;
    a=b;
    b=temp;}
      

  25.   


    趁早打消这个念头吧
    java 没有指针,不可能实现灵活的数据交换,封装只能针对特殊情况
      

  26.   

    同学们好,函数的传递有两种,值传递和引用传递,
    这道题是引用传递的典型题,应该这样写
    private static void swap(ref int num1,ref int num2){
    int temp;
    temp=num1;
    num1=num2;
    num2=temp;}
    这样我们就可以用了,
    int num1=1,num2=2;
    Swap(ref num1,ref num2);
      

  27.   

    借助临时变量的方法
    int t = x + y;
    x = t - x;
    y = t - y;
    或者
    int c=x;
    x=y;
    y=c;
    System.out.println ( x + "," + y );
      

  28.   


    童鞋,这是 java 板块,不是C#
      

  29.   

    int不行。不过Integer可以。LZ考虑一下吧。
      

  30.   


    int不行,Integer 也不行,Integer 有得到整数值的方法,但是没有设置整数值的方法
      

  31.   

    java中没有引用传递,只有值传递  上面这个交换值(public void  swap(int x,inty))可以使用传递对象啊不要在此纠结语言了,每种语言都有自己的方式处理
      

  32.   


    class Num {
     int x;
     int y;
    }public class Test2 {
    public static void swap(Num num) {
    num.x=num.x+num.y;
    num.y=num.x-num.y;
    num.x=num.x-num.y;
    }

    public static void main(String [] args){
    Num num = new Num();
    num.x = 10;
    num.y = 20;
    System.out.println(num.x+":"+num.y);
    swap(num);
    System.out.println(num.x+":"+num.y);

    用面向对象的方法实现。
      

  33.   


    你的代码里,要求被交换的两个数据必须是 Num 类的成员变量,适应性太差
      

  34.   

    swap(int a,int b)
    {a=a^b;
     b=a^b;
     a=a^b;
    }
    这样就可以在不借用其他变量下实现两个数的交换了
      

  35.   

    public class TransTwo {
    static int a;
    static int b; public static void main(String[] args) {
    a = 2;
    b = 5;
    swap(a, b);
    System.out.println("a=" + a);
    System.out.println("b=" + b);
    } public static void swap(int x, int y) {
    int array[] = new int[2];
    array[0] = y;
    array[1] = x;
    a = array[0];
    b = array[1];
    }}
      

  36.   


    不错,既然使用了全局变量,就没有必要去用数组做引用了吧public class TransTwo {
    static int a=2,b=5;
    public static void main(String[] args) {
    swap(a, b);
    System.out.println("a=" + a);
    System.out.println("b=" + b);
    } public static void  swap(int x, int y) {
    a=y;
    b=x;
    }}
      

  37.   

    int[] a= {1,2};
    void swap(int[] a) {
        //a[1]<->a[2];
    }
    这样就可以交换了。。
      

  38.   

    如把参数类型换成Integer呢,中间变量赋值的时候用 Integer.intValue();
      

  39.   

    Integer 对象一旦创建,里面包含的 int 值是不会能改变的,所以也不行
      

  40.   

    package vhow.org;/**
     * A instance of this class will have a ability to swap two integers.
     * 
     * @author null
     */
    class Swaper
    {
    int x, y; public Swaper(int x, int y)
    {
    super();
    this.x = x;
    this.y = y;
    } // The swap behavior is belong to a Swaper object.
    public Swaper swap()
    {
    return new Swaper(this.y, this.x);
    }
    }public class JavaDemo
    {
    public static void main(String[] args)
    {
    int x = 3;
    int y = 4; System.out.println("x: " + x + ", y: " + y); // If you want to swap two integers, you need a object who has the
    // ability
    // to swap. namely, you need a object that has the swap method. If there
    // is none is SDK, you should build such a object by yourself.
    Swaper swaper = new Swaper(x, y); x = swaper.swap().x;
    y = swaper.swap().y; System.out.println("x: " + x + ", y: " + y);
    }
    }
      

  41.   

    package vhow.org;class IntegerCanBeSwaped 
    {
    private int value; public IntegerCanBeSwaped(int value)
    {
    this.value = value;
    }

    public int getValue()
    {
    return value;
    } public void setValue(int value)
    {
    this.value = value;
    }
    }class Swaper
    {
    public static void swap(IntegerCanBeSwaped opt1, IntegerCanBeSwaped opt2)
    {
    opt1.setValue(opt1.getValue() + opt2.getValue());
    opt2.setValue(opt1.getValue() - opt2.getValue());
    opt1.setValue(opt1.getValue() - opt2.getValue());
    }
    }public class JavaDemo
    {
    public static void main(String[] args)
    {
    int x = 3;
    int y = 4; System.out.println("x: " + x + ", y: " + y);

    IntegerCanBeSwaped int1 = new IntegerCanBeSwaped(x);
    IntegerCanBeSwaped int2 = new IntegerCanBeSwaped(y);

    Swaper.swap(int1, int2);

    x = int1.getValue();
    y = int2.getValue(); System.out.println("x: " + x + ", y: " + y);
    }
    }
      

  42.   

    2.借助临时变量的方法
    public void swap(int x,inty) {int temp=x;
    x=y;
    y=temp;}这个是可以的,各位大虾可以去试试,2个integer,完全没问题
      

  43.   

    因为java中没有指针 而所谓的引用也逐渐被淡化了
    我这里有两种方法:【1】用全局变量传值
    public class F{ 
    public F(int x,int y){
    int z;
    z=x;x=y;y=z;
    a=x; b=y; 
    }
    public void getInfo(){
    System.out.println("交换后:a= "+a+",b="+b);
    }

    private static int a;  
    private static int b; 
    public static void main(String args[]){
    a=10;
    b=8;
    System.out.printf("交换前: a="+a+",b="+b+"\n");
    F w1=new F(a,b);  
            w1.getInfo(); } 
    }【2】将要交换的数作为对象的一个变量class T{
        int t;
    }
    public class G {
        public static void main(String args[]){
            T a=new T();
            T b=new T();
            a.t=8;
            b.t=10;
            System.out.println("交换前 :a="+a.t+"  ,b="+b.t);
            change(a,b);
            System.out.println("交换后 :a="+a.t+" ,b="+b.t);
        }
        public static void change(T a,T b){
            T c=new T();
            c.t=a.t; a.t=b.t; b.t=c.t;
        }
    }
      

  44.   

    使用IntHolder包装x和y,然后再交换
      

  45.   

    怎么看都不懂,刚接触java,不懂封装之类的专业术语,有没有简单点的方法?利用全局变量能实现吗
      

  46.   


    void SWAP(double[] a,double[] b,int i,int j)
    {
        double tmp = a[i];
        a[i] = b[j];
        b[j] = tmp;
    }