实现互换a,b功能注意是用public static void swap(int a,int b){} 方法名已经定死了 不能更改 用数组入参不行 返回值不行 用temp是无法实现互换的 试过都知道 请教实现方式如果封装起来再试呢?public static void swap(Integer a, Integer b){}又能实现不?

解决方案 »

  1.   

    不明白你的意思
    你说的是不是如何让a,b互换??
    a= a+b;
    b= a-b;
    a= a-b;
      

  2.   

    答:
    public static void swap(int a,int b){}  不行
    public static void swap(Integer a, Integer b){} 不行方法名已经定死了 不能更改 用数组入参不行 返回值不行 既然都这样"定死了",你也就死了互换这条心了.
      

  3.   

    这个问题是被实践证明了的不能实现的,a和b是不可能交换的
    因为java只有值传递
    public static void swap(int a,int b){} 
    public static void swap(Integer a, Integer b){}
    都不行!!!
      

  4.   

    a,b互换当然就是换完后变成b,a了
    我不是限制你非不能用temp,1楼那个跟temp本质相同,返回void死活是传不出来的,你试了就知道了
      

  5.   

    肯定不行,int是基本型,如果是void的话,打死你也换不了。
      

  6.   

    同意 这么死 这么换 有不是main函数 你是一个无返回值的方法
      

  7.   

    如果非要这么实现的话  
    你可以再里边调用一个有返回值的方法public static void swap(int a,int b){      swap2(a,b)
    } public static int swap2(int a,int b){

    但这种人肯定脑壳有包
      

  8.   

    大师说Java只能用值传递,您就死了这心吧。
      

  9.   

    As java method parameter,  basic data type is passed by value, but object is passed by address.
      

  10.   

    在你调用方法swap(a,b)的时候,传给方法的只是a,b的副本,只在swap()中有效,方法结束后副本被回收了,也就是说不管你怎么折腾a,b折腾的都不是a,b本身,a,b也从没被修改过。
      

  11.   

    只要记住,对象是传引用的就行。而基本数据类型是传值的。
    1. 如果是下面的方式,那么Test中的int值也是可改的。
    2. 如果Integer中也有一个int的类变量,那它的值也是可换的。
    3. 如果在方法中只能对方法的参数(对象)本身操作,是永远不能改变这个方法外的这个参数的引用的。因为方法传递的是这个引用的一个拷贝。public class IntegerTest {    public static void main(String[] args) {
            Test A = new Test();
            Test B = new Test();
            
            A.setValue(10);
            B.setValue(12);
            
            IntegerTest tt = new IntegerTest();
            System.out.println("Before A = " + A.getValue());
            System.out.println("Before B = " + B.getValue());        
            tt.swap(A, B);
            System.out.println("After A = " + A.getValue());
            System.out.println("After B = " + B.getValue());
            
        }
        public void swap(Test A, Test B) {
           int tmp = A.getValue();
            A.setValue(B.getValue());
            B.setValue(tmp);
        }
    }
     class Test {
         int a;
         public void setValue(int a) {
             this.a = a;
         }
         public int getValue() {
             return a;
         }
     }Before A = 10
    Before B = 12
    After A = 12
    After B = 10