日期:2014-05-20  浏览次数:20639 次

新手, 问个简单的问题
public   class   HelloWorld   {

/**
  *   @param   args
  */
public   static   void   swap(String   first,   String   second)   {
String   temp;
temp   =   first;
first   =   second;
second   =   temp;
}
public   static   void   main(String[]   args)   {
//   TODO   Auto-generated   method   stub
String   i   =   "hello ",   j   =   "world ";
System.out.print( "Hello   world! ");
System.out.print(i   +   "   "   +   j);
swap(i,   j);
System.out.print(i   +   "   "   +   j);
}
}

为啥程序运行后,   最后一个out.pring应该输出world   hello,   可是为什么还是hello   world呢?   错在哪里?   请指教,   谢谢



------解决方案--------------------
java的函数调用都是值传递,就是i和j的值传过去,并不是地址传递,
在swap中的first,second是另外两个对象,你实际交换的是他们两个,而并不是i和j
------解决方案--------------------
swap(i, j);

实际上是进行了对象拷贝.相当于 swap(first = i,second = j)
因此只交换了first 和 second
------解决方案--------------------
重点是参数的传递~
任何参数的传递都是其对象副本的引用.
在你程序中只是将对象副本传递给了方法~而对象本身没有发生实现的变换
所以输出依旧
------解决方案--------------------
由于字符串是一类比较特殊的对象,有一个字符串池,要实现你的要求,除非你进行引用传递,换一种其他的对象,如
public class HelloWorld {

/**
* @param args
*/
public static void swap(String [] strArray) {
String temp;
temp = strArray[0];
strArray[0] = strArray[1];
strArray[1] = temp;
}

public static void main(String[] args) {
// TODO Auto-generated method stub
String i = "hello ", j = "world ";
String strArray[] = new String[2];
strArray[0] = i;
strArray[1] = j;
System.out.println( "Hello world! ");
System.out.println(i + " " + j);
swap(strArray);
i = strArray[0];
j = strArray[1];
System.out.println(i + " " + j);
}
}