(66)ArrayList练习:自定义对象存入ArrayList,去除重复元素。迭代器指针移动解释

* 需求:将自定义对象作为元素存入到ArrayList集合中,并去除重复元素*
* 比如:存人对象,同姓名同年龄,视为同人,去除重复元素*
ArrayList:删除(remove)是要依赖equals方法,判断是否有该元素

import java.util.*;

/*
 * List集合判断元素是否相同,依据的是元素的equals方法
 */
public class People {
  private String name;
  private   int age;

  People(String name,int age){
      this.name=name;
      this.age=age;

  }
  /*
   * List中contains方法,底层调用的是equals方法,但是该方法比较的是对象的引用是否相同
   * 有时不满足实际需求,所以类中对equals方法进行复写,就会调用该方法。
   * 过程:第一个元素放入a2,判断第二个元素是否放入a2时,第二个元素调用本类中equals方法,
   * 与容器中的每个元素进行比较
   * 
   */
  public boolean equals(Object obj) {
      if(!(obj instanceof People))//集合中各种类型的元素,若不是人类型,则返回false
          return false;

      People p=(People)obj;
      System.out.println(this.name+"-----"+p.name);
      if(this.name==p.name&this.age==p.age)
          return true;


      return false;

  }

  public static  ArrayList singleElement(ArrayList al) {
      ArrayList a2=new ArrayList();
      Iterator it=al.iterator();
      while (it.hasNext()) {
          Object obj=it.next();
           if(!a2.contains(obj))
               a2.add(obj);

      }


      return a2;

  }
public String getName() {
    return name;
}

public int getAge() {
    return age;
}
}

public class PeopleDemo {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ArrayList al=new ArrayList();
        al.add(new People("张三",20));
        al.add(new People("李四",21));
        al.add(new People("王五",23));
        al.add(new People("李四",21));
        //al.add(new People("张三",20));

        System.out.println("remove 张三");

        //al.add(new People("张三",20));
        //al.add(new People("李四",21));//al.add(Object obj);等价于Object obj=new Person("张三",30);类型提升
        //Iterator it=al.iterator();
        /*while(it.hasNext()) {
            People p=(People) it.next();//向下转型
            System.out.println("姓名:"+p.getName()+"   年龄为:"+p.getAge());
        }*/
        ArrayList newArr=new ArrayList();
        newArr=People.singleElement(al);
        Iterator it=newArr.iterator();
        while(it.hasNext()) {
            People p=(People) it.next();//向下转型
            System.out.println("姓名:"+p.getName()+"   年龄为:"+p.getAge());
        }


    }

}

迭代器指针移动解释:
这里写图片描述

posted @ 2017-07-16 20:56  测试开发分享站  阅读(108)  评论(0编辑  收藏  举报