class Person //定义一个人的类,存放姓名、年龄。
{
private String name;
private int age;
Person(String name,int age)
{
setName(name);
setAge(age);
}
public void setName(String name)
{
this.name = name;
}
public void setAge(int age)
{
this.age = age;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public boolean equals(Object obj) //重写equals方法,因为Object类中只是比较地制值。
{
if(!(obj instanceof Person))
return false;
Person p = (Person)obj;
return this.name.equals(p.name) && this.age==p.age;
}
}
public class ArrayListTest
{
public static void main(String[] args)
{
ArrayList al = new ArrayList();
al.add(new Person("lisi01",20));
al.add(new Person("lisi02",21));
al.add(new Person("lisi03",23));
al.add(new Person("lisi03",23));
al.add(new Person("lisi04",25));
Iterator it = al.iterator();
while(it.hasNext())
{
Person p = (Person)it.next();
System.out.println("去重复前"+p.getName()+"---"+p.getAge());
}
System.out.println("--------------------------");
al = singleEmplement(al); // 调用去重复方法
it = al.iterator();
while(it.hasNext()) //输出去重复后的元素
{
Person p = (Person)it.next();
System.out.println("去重复后"+p.getName()+"---"+p.getAge());
}
}
public static ArrayList singleEmplement(ArrayList al) //定义一个去重复的方法
{
ArrayList newAl = new ArrayList();
Iterator it = al.iterator();
while(it.hasNext())
{
Object obj = it.next();
if(!(newAl.contains(obj)))
newAl.add(obj);