public class TTT {
  public void swap(String a,String b){
    String temp = new String("");
    temp=a.toString();
    a=b.toString();
    b=temp.toString();
    System.out.println("is inter a and b ="+a.toString()+" and "+b.toString());
  }
  public static void main(String[] args) {
String ss = new String("123");
    String bb= new String("456");
    TTT1.swap1(ss,bb);
   System.out.println("is outter a and b ="+ss.toString()+" and "+bb.toString());
}
}
输出为:
is inter a and b =456 and 123is outter a and b =123 and 456上面我这样子写是错的,其实ss、bb俩值只是在swap函数作用域里面交换了!
出了swap他们的值还是原来的值!我应如何写,多谢各位大虾!!

解决方案 »

  1.   

    因为传递的是reference所以直接做(像你这样)是肯定没有办法的,要想办法操作到内存(修改到内存),下面是一种解决办法,你看看吧。
    public class TTT {
      public void swap(String[] hehe){
        String temp = new String("");
        temp=hehe[0];
        hehe[0]=hehe[1];
        hehe[1]=temp;
        System.out.println("is inter a and b ="+hehe[0]+" and "+hehe[1]);
      }
      public static void main(String[] args) {
    String ss = new String("123");
        String bb= new String("456");
    String[] hehe = new String[2];
    hehe[0]=ss;
    hehe[1]=bb;
        TTT t = new TTT();
    t.swap(hehe);
       System.out.println("is outter a and b ="+hehe[0]+" and "+hehe[1]);
    }
    }
      

  2.   

    String只可读不可写,大概也只有用楼上的方法了。
      

  3.   

    用bluesmile979(笑着) 的方法比较合理,确实是这样!
      

  4.   

    这样子只不过是在一个数组里面交换两个值,这样子是能达到两个值的交换了,但是要是我必须swap(String a,String b),必须由这样的函数参数,那该如何实现!
      

  5.   

    或者写个类把string包一下,呵呵。这样要多写个类,随便你吧。
      

  6.   

    用String做参数肯定不行,试试用StringBuffer吧