天天看点

集合框架_去除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());
    }
  }
}