list对象复制问题

阅读更多

Java中的List.addAll复制对象

测试代码

import java.util.ArrayList;
import java.util.List;

/** 
* @author  yannis
* @date create time:2016年10月31日 上午11:10:31 
* @version 1.0 
* @parameter  
* @since  
* @return  
*/

public class Demo {
	public static void main(String[] args) {
		List list1 = new ArrayList();
		list1.add(new Person("li","2", 23));
		list1.add(new Person("wang","1", 30));
		list1.add(new Person("zhang","2", 40));
		list1.add(new Person("hu","2", 35));
		list1.add(new Person("chen","1", 60));
		
		List list2 = new ArrayList();
		list2.addAll(list1);
		list2.get(0).setName("hanmeimei");
		
		list1.get(1).setName("kkkk");

		for(Person person:list1){
			System.out.println(person.name);
		}
		
		for(Person person:list2){
			System.out.println(person.name);
		}
	}
	
	
	static class Person{
		private String name;
		private String sex;
		private Integer age;
		
		public Person(String name, String sex, Integer age) {
			super();
			this.name = name;
			this.sex = sex;
			this.age = age;
		}
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
		public String getSex() {
			return sex;
		}
		public void setSex(String sex) {
			this.sex = sex;
		}
		public Integer getAge() {
			return age;
		}
		public void setAge(Integer age) {
			this.age = age;
		}
		
	}
}

 通过测试发现,无论此时修改list1,或者list2 都会影响到两个list.运行结果如下

hanmeimei
kkkk
zhang
hu
chen
hanmeimei
kkkk
zhang
hu
chen

 

 由此可见,使用list.addAll只是把后者的对象的地址指向复制给了前面的list。所以造成一改全改

你可能感兴趣的:(java,list)