你的位置:首页 > Java教程

[Java教程]【Java学习笔记】集合框架定义功能去除ArrayList中的重复元素


 1 import java.util.ArrayList; 2 import java.util.Iterator; 3  4 import cn.itcast.p1.bean.Person; 5  6 public class ArrayListTest2 { 7  8   public static void main(String[] args) { 9 10     11     ArrayList al = new ArrayList();12     13     al.add(new Person("lisi1",21));14     al.add(new Person("lisi2",22)); //与28行的Person,内容相同,地址不同15     al.add(new Person("lisi3",23));16     al.add(new Person("lisi4",24));17     al.add(new Person("lisi2",22));18     al.add(new Person("lisi3",23));19     20     System.out.println(al);21     22     al = getSingleElement(al);23     24     System.out.println(al);25     26     System.out.println(al.remove(new Person("lisi2",22)));//remove内部是用equals来判断删除内容27     System.out.println(al);28 29   }30 31   32 33   private static ArrayList getSingleElement(ArrayList al) {34     //1.定义一个临时容器35     ArrayList temp = new ArrayList();36     37     //2.迭代al集合38     Iterator it = al.iterator();39     40     while (it.hasNext())41     {42       Object obj = it.next();43       44       //3.判断被迭代到的元素是否在临时容器中存在45       if (!temp.contains(obj))46       {47         temp.add(obj);48       }49     }50     51     return temp;52   }53 54 }