小弟是java初学者,以下的程序是测试交换两个对象的方法实现。但是运行后却交换不了。我查阅了书,书中说java的参数传递类型只有“值传递”。那么如果想实现这样一个交换两个对象的方法具体应该怎么写呢?(我知道c++很容易实现的)
。谢谢回答。
public class mytest {
public static void main(String[] args) {
ObjectSample o1 = new ObjectSample("hello");
ObjectSample o2 = new ObjectSample("你好");
System.out.println("before swap o1:"+o1.getTitle()+" o2:"+o2.getTitle());
swapObject(o1, o2);
System.out.println("after swap o1:"+o1.getTitle()+" o2:"+o2.getTitle());
}
static void swapObject(ObjectSample o1, ObjectSample o2){
ObjectSample temp = new ObjectSample("temp");
temp = o1;
o1 = o2;
o2 = temp;
}
}
class ObjectSample{
private String title;
ObjectSample(String title){
this.title = title;
}
public String getTitle(){
return title;
}
}
------解决方案--------------------------------------------------------
- Java code
public class mytest { public static void main(String[] args) { ObjectSample o1 = new ObjectSample("hello"); ObjectSample o2 = new ObjectSample("你好"); System.out.println("before swap o1:" + o1.getTitle() + " o2:" + o2.getTitle()); swapObject(o1, o2); System.out.println("after swap o1:" + o1.getTitle() + " o2:" + o2.getTitle()); } static void swapObject(ObjectSample o1, ObjectSample o2) { String tmp = o1.getTitle(); o1.setTitle(o2.getTitle()); o2.setTitle(tmp); }}class ObjectSample { private String title; ObjectSample(String title) { this.title = title; } public String getTitle() { return title; } public void setTitle(String title){ this.title = title; }}
------解决方案--------------------------------------------------------
java中虽然可以叫“值传递” ,但是分开讲会更好些,对于基本数据类型我们叫“值传递”,对于对象叫“引用传递”更好。当然其实也都可以理解为“传值”。而你要交换的是属性的值,传递引用并不能改变其对象的属性和方法。当然那样是不行的。
------解决方案--------------------------------------------------------
java中对象是引用值的传递,你的
System.out.println("before swap o1:"+o1.getTitle()+" o2:"+o2.getTitle());
swapObject(o1, o2); //没有交换到
System.out.println("after swap o1:"+o1.getTitle()+" o2:"+o2.getTitle());
}
static void swapObject(ObjectSample o1, ObjectSample o2){ //相当与在方法体中交换了两个局部的对象,对你上面的o1,o2没影响
ObjectSample temp = new ObjectSample("temp");
temp = o1;
o1 = o2;
o2 = temp;
}