一、去除ArrayList中的重复元素
public class Person {
public String name;
public int age;
public Person(String name,int age){
this.name = name;
this.age = age;
}
public boolean equals(Object obj){ //覆盖equals方法
if(this == obj)
return true;
if(!(obj instanceof Person)){
throw new ClassCastException("类型错误");
}
Person p = (Person) obj;
return this.name.equals(p.name) && this.age == p.age;
}
}
import java.util.ArrayList;
import java.util.Iterator;
public class ArrayListTest {
public static void main(String[] args) {
ArrayList a1 = new ArrayList();
a1.add(new Person("abc1",1));
a1.add(new Person("abc2",1));
a1.add(new Person("abc1",1));
a1.add(new Person("abc2",1));
a1.add(new Person("abc",1));
// a1 = getSingleElement(a1); //去除字符串
a1 = getSingleElement2(a1); //去除自定义对象
Iterator it = a1.iterator();
while(it.hasNext()){
Person p = (Person)it.next();
System.out.println(p.name+"...."+p.age);
}
}
private static ArrayList getSingleElement2(ArrayList a1) {
//定义临时容器
ArrayList temp = new ArrayList();
//迭代集合
Iterator it = a1.iterator();
while(it.hasNext()){
Object obj = it.next();
//判断被迭代到的元素是否在临时容器中存在
if(!temp.contains(obj)){
temp.add(obj);
}
}
return temp;
}
public static ArrayList getSingleElement(ArrayList a1) {
//定义临时容器
ArrayList temp = new ArrayList();
//迭代集合
Iterator it = temp.iterator();
while(it.hasNext()){
Object obj = it.next();
//判断被迭代到的元素是否在临时容器中存在
if(!temp.contains(obj)){
temp.add(obj);
}
}
return temp;
}
}