ArrayList 实现删除重复元素(元素为对象类型)
package 集合;
import java.util.ArrayList;
import java.util.Iterator;
/*
* 删除集合中的重复的元素(元素是对象形式的)
*
* List集合判断元素是否相同,依据是元素的equals()方法,其他集合和这个不一样,contains的底层比较原理就是equals。
* remove()方法的底层原理也是equals()方法
* */
class Person{
String name;
int age;
public Person(){}
public Person(String name,int age){
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
//重写Person的equals方法
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;
}
}
public class ArrayListTest2 {
public static void main(String[] args) {
ArrayList al = new ArrayList();
al.add(new Person("lisi01",20));
al.add(new Person("lisi02",20));
al.add(new Person("lisi03",20));
al.add(new Person("lisi04",20));
al.add(new Person("lisi02",20));
al.add(new Person("lisi03",20));
al =noReplaceElement(al);
Iterator it = al.iterator();
while(it.hasNext()){
Person person = (Person)it.next(); //it.next()返回的是Object类型,必须要强转成Person
System.out.println(person.getName()+":"+person.getAge());
}
}
//定义取出重复元素的方法
public static ArrayList noReplaceElement(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;
}
}