1 package cn.itcast.p3.arraylist.test;
2
3 import java.util.ArrayList;
4 import java.util.Iterator;
5
6 import com.sun.org.apache.bcel.internal.generic.NEW;
7
8 import cn.itcast.p.bean.Person;
9 import cn.itcast.p4.hashset.demo.HashSetDemo;
10
11 /*
12 * 定义功能去除ArrayList中的重复元素
13 */
14 public class ArrayListTest2 {
15
16 public static void main(String[] args) {
17 // TODO Auto-generated method stub
18
19 ArrayList al = new ArrayList();
20 al.add(new Person("list1",21));
21 al.add(new Person("list2",22));
22 al.add(new Person("list3",23));
23 al.add(new Person("list4",24));
24 al.add(new Person("list4",24));
25 al.add(new Person("list4",24));
26
27 System.out.println(al);
28
29 al = getSingleElement(al);
30
31 System.out.println(al);
32
33 // System.out.println(al.remove(new Person("list2",22)));//remove 也是和equals相关
34
35 // System.out.println(al);
36
37 // singleDemo();
38 }
39
40 private static ArrayList getSingleElement_2(ArrayList al) {
41 // TODO Auto-generated method stub
42 return null;
43 }
44
45 /**
46 *
47 */
48 public static void singleDemo() {
49 ArrayList al = new ArrayList();
50 al.add("abc1");
51 al.add("abc2");
52 al.add("abc2");
53 al.add("abc1");
54 al.add("abc");
55 System.out.println(al);
56 al = getSingleElement(al);
57 System.out.println(al);
58
59
60 }
61 public static ArrayList getSingleElement(ArrayList al) {
62 //1,定义一个临时容器
63 ArrayList temp = new ArrayList();
64
65 //2,迭代al集合
66 Iterator it = al.iterator();
67
68 while(it.hasNext()) {
69 Object obj = it.next();
70 //3,判断被迭代到的元素是否在临时容器存在。
71 if (!temp.contains(obj)) {//contains也是依据equals,如果person类equals没有重写,比较的还是地址值
72 temp.add(obj);
73 }
74 }
75
76 return temp;
77 }
78
79
80
81 }