是reference的,但你的swap方法有错:MyClass temp= new MyClass(lhs);
lhs= new MyClass(rhs);
rhs=temp;用拷贝构造函数来进行内容复制

解决方案 »

  1.   

    内容是可以复制,但swap的意思是地址交换而不是内容交换哦
      

  2.   

    如果你要交换地址,需要用好像c++那样的双重指针才行,因为你传到swap里面的rhs和lhs,是swap函数的内部变量,怎么改变他们的指针,都指示影响到这两个变量的生存期内,也是就是swap函数内。对他们的外部没有影响,注意,这两个地址是用值的方式传进去的。你传的是这两个指针的内容(内存地址),不是指向这两个指针的指针,也不是这两个指针指向的内存内容。你要用这样的swap函数进行交换,就只能交换内容,因为你根本操作不了原来的两个内存引用对象。没有规定swap是交换指针的。
    class TestClass{
      public int c;
    }public class testapp {
      //Construct the application
      public testapp() {
      }
      public void swap(TestClass tc1,TestClass tc2)
      {
        TestClass temptc=tc1;
        tc1=tc2;
        tc2=temptc;
        System.out.println("tc1("+tc1+") = "+ tc1.c + "     tc2("+tc2+") = "+tc2.c);
      }
      //Main method
      public static void main(String[] args) {
        TestClass tc1,tc2;
        tc1=new TestClass();
        tc2=new TestClass();
        tc1.c=1;
        tc2.c=2;
        testapp ta=new testapp();
        ta.swap(tc1,tc2);
        System.out.println("tc1("+tc1+") = "+ tc1.c + "     tc2("+tc2+") = "+tc2.c);
      }
    自己看看结果如何吧。特别注意一下里面的内存指针,传到swap里面已经变了,只不过其内容是指向同一个内存块而已。