* 需求:
* 使用ArrayList添加重复的对象类型(自定义对象),如何去除重复自定义对象
* 如果该对象的成员信息一致,认为是同一个人
* contains()底层依赖于equals()方法,而且equals()方法
* 默认比较的是地址值是否相同,目前这个类Student类(自定义类)
*
* 如果想将重复的对象去掉,需要在自定义的类中重写Object类中equals()方法,让它比较
* 成员信息是否一致
public class ArrayTest3 {
public static void main(String[] args) {
//创建ArrayList集合对象
ArrayList<Student>array=new ArrayList<Student>();
//创建几个学生对象
Student s1=new Student("张三",20);
Student s2=new Student("李四",30);
Student s3=new Student("王五",40);
Student s4=new Student("赵六",50);
Student s5=new Student("张三",20);
Student s6=new Student("李四",30);
//给旧集合添加元素
array.add(s1);
array.add(s2);
array.add(s3);
array.add(s4);
array.add(s5);
array.add(s6);
//创建一个新集合
ArrayList<Student>newArray=new ArrayList<Student>();
//遍历旧集合
for(Student s:array) {
//使用新的集合判断是否包含元素
if(!newArray.contains(s)) {
//将学生对象添加到新集合中
newArray.add(s);
}
}
//遍历新集合
for(Student s:newArray) {
System.out.println(s.getName()+"--"+s.getAge());
}
}
}