Java交换对象

1. 概述

在java中,参数传递是通过传值(对于对象类型,传递的是引用的拷贝),所以常规的交换实现不了两个对象的交换,下面是测试代码:

 


import org.apache.commons.beanutils.BeanUtils;

public class Employee {
	// Properties
	private int id;
	private String name;
	
	// Constructors
	public Employee() {
	}
	
	public Employee(int id, String name) {
		this.id = id;
		this.name = name;
	}
	
	// get、set methods
	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
	// 无效的交换
	public static void swap(Employee x, Employee y) {
		Employee temp = x;
		x = y;
		y = temp;
	}
	
	// 使用 BeanUtils 方法的有效交换
	public static void swapByBeanUtils(Employee x, Employee y) {
		try {
			// clone x to temp
			Employee temp = (Employee)BeanUtils.cloneBean(x);
			// copyProperties from y to x
			BeanUtils.copyProperties(x, y);
			// copyProperties from temp to y
			BeanUtils.copyProperties(y, temp);
			// then, the Properties values of x,y has been swaped.
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}
	
	// 有人提出使用交换数组等集合里的元素 来实现交换,这样也是无效的
	public static void swapByArray(Object[] a, int i, int j) {
	    Object t = a[i];
	    a[i] = a[j];
	    a[j] = t;
	}
	
	public static void main(String[] args) {
		Employee a = new Employee(1, "Bob");
		Employee b = new Employee(2, "Jack");
		
		// 直接方法调用交换 -- NO
//		swap(a, b);
		
		// 利用BeanUtils交换 -- YES
//		swapByBeanUtils(a, b);
		
		// 利用 交换数据 思想 -- NO
//		Object[] o = {a, b};
//		swapByArray(o, 0, 1);
		
 		// 直接交换 -- YES
//		Employee temp = a;
//		a = b;
//		b = temp;
		
		System.out.println(a);
		System.out.println(b);		
	}
	
	// method for print
	public String toString() {
		StringBuilder sb = new StringBuilder();
		sb.append("id: ").append(id).append(" name: ").append(name);
		return sb.toString();
	}
}

 2. 结论

在java中,对象引用是通过值来传递的,方法不能修改参数指向新的对象。

 

注:需加载 BeanUtils包

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值