import java.util.ArrayList;
import java.util.Iterator; import cn.itcast.p1.bean.Person; public class ArrayListTest2 { public static void main(String[] args) { ArrayList al = new ArrayList(); al.add(new Person("lisi1",21));
al.add(new Person("lisi2",22)); //与28行的Person,内容相同,地址不同
al.add(new Person("lisi3",23));
al.add(new Person("lisi4",24));
al.add(new Person("lisi2",22));
al.add(new Person("lisi3",23)); System.out.println(al); al = getSingleElement(al); System.out.println(al); System.out.println(al.remove(new Person("lisi2",22)));//remove内部是用equals来判断删除内容
System.out.println(al); } private static ArrayList getSingleElement(ArrayList al) {
//1.定义一个临时容器
ArrayList temp = new ArrayList(); //2.迭代al集合
Iterator it = al.iterator(); while (it.hasNext())
{
Object obj = it.next(); //3.判断被迭代到的元素是否在临时容器中存在
if (!temp.contains(obj))
{
temp.add(obj);
}
} return temp;
} }