package com.lee.list;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import com.lee.model.Person;
public class ListAddChangeList {
/*[com.lee.model.Person@2510bb7, com.lee.model.Person@16d81c91]
[com.lee.model.Person@2510bb7, com.lee.model.Person@16d81c91]
[com.lee.model.Person@2510bb7, com.lee.model.Person@16d81c91]
[null, null]*/
//实验证明,list保存的是p1 p2 指向的内存地址,这块内存地址的值可以通过p1 p2去修改里边的值
//但是改变p1 p2的指向并不能改变这块内存地址的值,所以当p1 = null时
//list保存的p1所指向的内存地址还是不会改变,还是会有值
@Test
public void t1(){
List<Person> list = new ArrayList<Person>();
Person p1 = new Person("n1",11);
Person p2 = new Person("n2", 22);
list.add(p1);
list.add(p2);
// p1 = null;
// p2 = null;
//System.out.println(list.toString());
print(list);
p1.setAge(15);
List<Person> list2 = new ArrayList<Person>();
list2.add(list.get(0));
list2.add(list.get(1));
list.set(0, null);
list.set(1, null);
//System.out.println(list2.toString());
p1.setAge(166);
p1 = null;
p2 = null;
System.out.println("****p1.setAge(16)****");
print(list2);
// p1 = null;
// p2 = null;
p1.setAge(17);
System.out.println("***********");
print(list2);
//System.out.println(list2.toString());
// list2.set(0, null);
// list2.set(1, null);
//System.out.println(list2.toString());
p1.setAge(17);
print(list2);
}
private void print(List<Person> list) {
for(Person person : list){
System.out.print(person.getName() + " " + person.getAge() + " ");
}
if(list.size() == 0){
System.out.println("empty");
}
System.out.println();
}
}
list中对象、值保存的解释
最新推荐文章于 2022-08-26 14:52:46 发布