首页 > 代码库 > java ArrayList去重
java ArrayList去重
定义一个Person的类,存入ArrayList集合中,去除重复元素,定义:名字相同的和年龄都相同的为重复元素。
取重
public class Qu {
public static void main(String[] args) {
Sa2 a = new Sa2("张三",20);
Sa2 a1 = new Sa2("张三",30);
Sa2 a3 = new Sa2("张三",20);
ArrayList<Sa2> list = new ArrayList<Sa2>();
list.add(a);
list.add(a1);
list.add(a3);
ArrayList<Sa2> list1 = quCong(list);
System.out.println(list1);
}
public static ArrayList<Sa2> quCong(ArrayList<Sa2>list){
ArrayList<Sa2> list1=new ArrayList<Sa2>();
ListIterator<Sa2> it = list.listIterator();
while(it.hasNext()){
Sa2 str = it.next();
if(!list1.contains(str)){
list1.add(str);
}
}
return list1;
}
}
————————————————————————————————————————————————————
public class Sa2 {
String name;
int age;
public Sa2(String name,int age){
this.name=name;
this.age=age;
}
public int HashCode(){//重写,把底层改变。
return 1;
}
public boolean equals(Object obj){
if(obj instanceof Sa2){
Sa2 p = (Sa2)obj;
return this.name.equals(p.name) && this.age == p.age;
}
return false;
}
public String toString(){
return "Sa2[name"+ name+",age="+age+"]";
}
}
java ArrayList去重