java怎么拦截某个对象
232
2022-09-19
集合框架_去除ArrayList集合中的重复自定义对象元素案例
package cn.itcast_04;public class Student { private String name; private int age; public Student() { super(); // TODO Auto-generated constructor stub } public Student(String name, int age) { super(); this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Student other = (Student) obj; if (age != other.age) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; }}
package cn.itcast_04;import java.util.ArrayList;import java.util.Iterator;/* * 需求:去除集合中自定义对象的重复值(对象的成员变量值都相同) * * 我们按照和字符串上一样的操作,出现了问题。 * 为什么呢? * 我们必须思考那里会出问题? * 通过简单的分析,我们知道问题出现在了判断上。 * 而这个判断功能有是集合自已提供的,所以我们如果想很清楚的知道它是如何判断的的,就应该去看源码。 * * contains()方法底层依赖的是equals()方法。 * 而我们的学生类中没有equals()方法,这个时候,默认使用的是它父亲Object的equals()方法 * Object()的equals()默认比较提 地址值,所以,它们进去了,因为new的东西,地址值都不同。 * 按照我们自已的需求,比较成员变量的值,重写equals()方法即可。 * 自动生成即可。 */public class ArrayListTest3 { public static void main(String[] args) { // 创建集合对象 ArrayList array = new ArrayList(); // 创建学生对象 Student s1 = new Student("孙悟空", 550); Student s2 = new Student("唐僧", 26); Student s3 = new Student("猪八戒", 33); Student s4 = new Student("沙僧", 22); Student s5 = new Student("白龙马", 3000); Student s6 = new Student("孙悟空", 550); Student s7 = new Student("猪八戒", 33); Student s8 = new Student("沙僧", 29); Student s9 = new Student("沙僧", 22); Student s10 = new Student("白龙马", 3000); // 把学生对象添加到集合对象中 array.add(s1); array.add(s2); array.add(s3); array.add(s4); array.add(s5); array.add(s6); array.add(s7); array.add(s8); array.add(s9); array.add(s10); // 创建新集合 ArrayList newArray = new ArrayList(); // 遍历旧集合判断相同元素 for (int x = 0; x < array.size(); x++) { Student stu = (Student) array.get(x); if (!newArray.contains(stu)) { newArray.add(stu); } } // 遍历新集合 Iterator it = newArray.iterator(); while (it.hasNext()) { Student ss = (Student) it.next(); System.out.println(ss.getName() + "---" + ss.getAge()); } }}
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~