集合元素去重复contains()方法使用

 1 package cn.arraylist.com;
 2 
 3 import java.util.ArrayList;
 4 import java.util.Iterator;
 5 /*
 6  * 集合去除相同元素原理:用集合和空集合对比,遍历集合>>如果空集合中没有有当前元素,则把当前元素添加到空集合中,
 7  * 最后遍历新集合
 8  */
 9 public class ArraylistDemo {
10 
11     public static void main(String[] args) {
12         // TODO Auto-generated method stub
13         ArrayList arraylist = new ArrayList();
14         arraylist.add("li");
15         arraylist.add("liu");
16         arraylist.add("huang");
17         arraylist.add("li");
18         arraylist.add("huang");
19         // 创建集合2
20         ArrayList arraylist2 = new ArrayList();
21 
22         // 迭代器
23         Iterator it = arraylist.iterator();
24         while (it.hasNext()) {
25             String s = (String) it.next();
26             if (!arraylist2.contains(s)) {//如果新集合不包含当前元素
27                 arraylist2.add(s);//添加当前元素到新集合
28             }
29         }
30         // 遍历新集合
31         Iterator it2 = arraylist2.iterator();
32         while (it2.hasNext()) {
33             String ss = (String) it2.next();
34             System.out.println(ss);
35         }
36     }
37 }

猜你喜欢

转载自www.cnblogs.com/yschung/p/9316543.html
今日推荐