/*contains和remove用的比较方法都是equals方法*/
import java.util.*;
class removeObjectElement
{
public static void main(String[] args)
{
ArrayList al = new ArrayList();
al.add(new Person("lisi",33));
al.add(new Person("lisi",34));
al.add(new Person("lisi",35));
al.add(new Person("lisi",35));
al.add(new Person("lisi",36));
al.add(new Person("lisi",36));
al=singleElement(al);
Iterator it = al.iterator();
while(it.hasNext())
{
//因为ArrayList里面添加对象时都被强制转换成Object类型
Person p=(Person)it.next();
System.out.println(p.getName()+"::"+p.getAge());
}
}
public static ArrayList 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 this.name;
}
public int getAge()
{
return this.age;
}
//复写equals方法
public boolean equals(Object obj)
{
Person p = (Person)obj;
return this.name.equals(p.getName()) && this.age==p.getAge();
}
}
【java编程】Collection类之ArrayList去除自定义对象的重复元素
最新推荐文章于 2024-03-26 14:34:00 发布