本帖最后由 张文强 于 2012-6-3 07:48 编辑
/*
功能:存储人类对象 并去除重复元素
按照同名年龄相同为同一元素
1.创建Person类
2.复写equals方法,对传入的元素判断
3.创建对象实例
4.取出元素
*/
import java.util.*;
class Person
{
private String name;
private int age;
Person(String myName,int age)
{
this.name=name;
this.age=age;
}
public boolean equals(Object obj)
{
if(!(obj instanceof Person))
return false;
Person p = (Person)obj;
return this.name.equals(p.name) && this.age==age;
}
public int myAge()
{
return age;
}
public String myName()
{
return name;
}
}
public class PersonDemo
{
public static void main(String args[])
{
ArrayList pr = new ArrayList();
pr.add(new Person("zhangsan1",51));
pr.add(new Person("zhangsan2",52));
pr.add(new Person("zhangsan3",53));
pr.add(new Person("zhangsan3",56));
pr.add(new Person("zhangsan3",53));
pr.add(new Person("zhangsan4",54));
pr.add(new Person("zhangsan5",55));
//sop(pr);
pr=guolu(pr);
Iterator it = pr.iterator();
while(it.hasNext()) //打印过滤后的元素
{
Person p = (Person)it.next();
sop(p.myName()+":::"+p.myAge());
}
}
/* public static ArrayList guolu(ArrayList al)//过滤重复元素;
{
ArrayList newal = new ArrayList();
Iterator tt = al.iterator();
while(tt.hasNext())
{
Person p1 = (Person)tt.next();
if(!newal.contains(p1))
newal.add(p1);
}
return newal;
}
public static void sop(Object obj)
{
System.out.println(obj);
}
*/
public static ArrayList guolu(ArrayList al)
{
ArrayList newa = new ArrayList();
Iterator tt = al.iterator();
while(tt.hasNext())
{
Person aa = (Person)tt.next();
if(!newa.contains(aa))
newa.add(aa);
}
return newa;
}
public static void sop(Object obj)
{
System.out.println(obj);
}
} |
|