日期:2014-05-20 浏览次数:20983 次
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;
}