package com.test;
import java.util.ArrayList;
import java.util.Iterator;
public class Demo5 {
//要求将Person类的对象存入List并去重,去重的规则:按照人的年龄和姓名比较.只要年龄和姓名一致就认为是一个人.
public static void main(String[] args) {
ArrayList list = new ArrayList<>();//
list.add(new Person("bingbing1", 20));
list.add(new Person("bingbing1", 20));
list.add(new Person("bingbing2", 23));
list.add(new Person("bingbing3", 26));
System.out.println(list);
ArrayList list1 = new ArrayList<>();//创建一个空的,list1用来临时存
Iterator iterator = list.iterator();
while (iterator.hasNext()) {
Object object = (Object) iterator.next();
if (!list1.contains(object)) {
list1.add(object);
}
}
System.out.println(list1);
}
}
class Person{
String name;
int age;
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
@Override
public String toString() {//转成字符串
return "Person [name=" + name + ", age=" + age + "]";
}
//:按照人的年龄和姓名比较.只要年龄和姓名一致就认为是一个人.
public boolean equals(Object obj) {
if (!(obj instanceof Person)) {
throw new ClassCastException();
}
//向下转型
Person person = (Person)obj;//obj转成Person
return this.age==person.age && this.name.equals(person.name);//equals判断两个内容是否相等
}
}