使用ArrayList存储自定义对象并遍历
import java.util.ArrayList;
import java.util.Iterator;
public class ArrayListDemo1 {
public static void main(String[] args) {
//创建ArrayList集合对象
ArrayList arrayList = new ArrayList();
//创建5个学生对象
Student s1 = new Student("范闲", 23);
Student s2 = new Student("范思辙", 22);
Student s3 = new Student("鸡腿菇凉", 20);
Student s4 = new Student("范若若", 21);
Student s5 = new Student("庆帝", 50);
//将学生对象添加到集合中
arrayList.add(s1);
arrayList.add(s2);
arrayList.add(s3);
arrayList.add(s4);
arrayList.add(s5);
//遍历的第一种方式1:迭代器遍历
//获取迭代器对象
Iterator iterator = arrayList.iterator();
while (iterator.hasNext()) {
Student s = (Student) iterator.next();
System.out.println(s.getName() + "---" + s.getAge());
} System.out.println("=========================================");
//遍历的第一种方式1:get()和size()方法结合
for (int i = 0; i < arrayList.size(); i++) {
Student student = (Student) arrayList.get(i);
System.out.println(student.getName() + "---" + student.getAge());
}
}
}
去除集合中自定义对象的重复值(对象的成员变量值都相同,姓名和年龄相同)
我们按照处理字符串的形式处理重复的自定义对象,发现结果并没有去重
为什么呢?
要想知道为什么,就得知道问题处在了哪一行代码
经过简单的分析后,我们发现问题出现了在判断的时候出现了。
因为只有当if里面是true的时候,才添加到新集合中,
说明我们的代码一直都是true,换句话说,contains()方法并没有生效
怎么改呢?要想知道怎么改,看一看contains内部是怎么实现的。
底层调用的是元素的equals方法,又因为我们Student类没有重写equals方法
调用的是父类Object类中的equals方法,比较的是地址值,所以contains()
结果永远是true,if判断永远判断的是新集合不包含,就添加到新集合中,所以
产生了没有去重的效果。
解决办法:元素类重写equals()方法
public class ArrayListTest2 {
public static void main(String[] args) {
ArrayList list = new ArrayList();
Student s1 = new Student("朱佳乐", 18);
Student s2 = new Student("吕常福", 19);
Student s3 = new Student("陶华根", 20);
Student s4 = new Student("朱佳乐", 18);
Student s5 = new Student("朱佳乐", 19);
list.add(s1);
list.add(s2);
list.add(s3);
list.add(s4);
list.add(s5);
System.out.println(list);
System.out.println("================================");
ArrayList list2 = new ArrayList();
Iterator iterator = list.iterator();
while (iterator.hasNext()){
Student s = (Student) iterator.next();
if(!list2.contains(s)){
list2.add(s);
}
}
System.out.println(list2);
}
}



