/*
需求:用ArrayList集合存储自定义对象人,并去除相同元素,姓名和年龄相同,视为对象相同
*/
import java.util.*;
class Person
{
private String name;
private int age;
Person(String name,int age){
this.name=name;
this.age=age;
}
public String getName(){
return name;
}
public int getAge(){
return age;
}
//自定义equals方法,判断两个Person对象是否相同
public boolean equals(Object obj){
if(!(obj instanceof Person))
return false;
Person p=(Person)obj;
return this.getName().equals(p.getName())&&this.age==p.age;
}
public String toString(){
return this.name+":"+this.age;
}
}
class ArrayListTest2
{
public static void main(String[] args)
{
ArrayList al=new ArrayList();
al.add(new Person("张三",29));
al.add(new Person("李四",29));
al.add(new Person("王五",31));
al.add(new Person("张三",29));
al.add(new Person("赵六",30));
al.add(new Person("李四",29));
sop(al);
al=(ArrayList)getSingleElements(al);
sop(al);
}
//获取单个元素
public static List getSingleElements(List list){
ArrayList al=new ArrayList();
Iterator it=list.iterator();
while(it.hasNext()){
Object obj=it.next();
if(!al.contains(obj))
al.add(obj);
}
return al;
}
public static void sop(Object obj){
System.out.println(obj);
}
} |
|