集合元素去重复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 }

 

转载于:https://www.cnblogs.com/yschung/p/9316543.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值