代码分享:- package example;
- import java.util.*;
- public class QuChong2
- {
- public static void main(String[] args)
- {
- ArrayList al=new ArrayList();
- al.add(new Person("zhangsan1",20));
- al.add(new Person("zhangsan2",22));
- al.add(new Person("zhangsan3",21));
- al.add(new Person("zhangsan2",20));
- al.add(new Person("zhangsan3",21));
-
- al=(ArrayList) singleElement(al);//去重元素
- Iterator it=al.iterator();
- //迭代取出元素
- while(it.hasNext())
- {
- Person p=(Person) it.next();
- System.out.println(p.getName()+"..."+p.getAge());
- }
- }
-
- //去重元素
- public static List singleElement(ArrayList al)
- {
- ArrayList newAl=new ArrayList();
- Iterator it=al.iterator();
-
- while(it.hasNext())
- {
- Object obj=it.next();
- if(!newAl.contains(obj))
- newAl.add(obj);
- }
- return newAl;
- }
- }
- 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.name.equals(p.name) && this.age==p.age;
- }
-
- }
复制代码
|
|