前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >java中集合类中Collection接口中的Set接口的常用方法熟悉

java中集合类中Collection接口中的Set接口的常用方法熟悉

作者头像
别先生
发布2017-12-29 18:36:07
1.2K0
发布2017-12-29 18:36:07
举报
文章被收录于专栏:别先生别先生

1:Set集合由Set接口和Set接口的实现类组成,Set接口继承了Collection接口,因为包含Collection接口的所有方法。

2:由于Set接口中不允许存在重复值,因此可以使用Set集合中addAll()方法,将Collection集合添加到Set集合中并除掉重复值

3:案例要求,创建一个List集合对象,并往List集合中添加元素。再创建一个Set集合,利用addAll()方法将List集合对象存入到Set集合中并除掉重复值,最后打印Set集合中的元素

 1 package com.ning;
 2 
 3 import java.util.*;
 4 
 5 public class Demo02 {
 6 
 7     public static void main(String[] args) {
 8         // TODO Auto-generated method stub
 9         List<String> list=new ArrayList<String>();//创建List集合
10         list.add("b");//将List集合中添加元素
11         list.add("a");
12         list.add("c");
13         list.add("q");
14         list.add("c");
15         Set<String> set=new HashSet<String>();//创建List集合对象
16         set.addAll(list);//将List集合添加到Set集合中
17         set.add("111");
18         set.remove("111");
19         Iterator<String> it=set.iterator();//创建Set迭代器
20         System.out.println("集合中的元素是:");
21         while(it.hasNext()){
22             System.out.print(it.next()+"\t");
23         }
24         
25         
26         
27     }
28 
29 }

1:要使用Set集合,通常情况下需要声明为Set类型,然后通过Set接口类来实例化。Set接口的实现类常用HashSet和TreeSet类。

Set<String> set=new HashSet<String>();

Set<String> set=new TreeSet<String>();

2:由于集合中对象是无序的,遍历Set集合的结果与插入Set集合的顺序并不相同

 1 package com.ning;
 2 
 3 public class People {
 4     
 5     private String name;
 6     private long id_card;
 7     public People(String name,long id_card){
 8         this.name=name;
 9         this.id_card=id_card;
10     }
11     
12     public void setId_card(long id_card){
13         this.id_card=id_card;
14     }
15     public long getId_card(){
16         return id_card;
17     } 
18     
19     public void setName(String name){
20         this.name=name;
21     }
22     public String getName(){
23         return name;
24     }
25     
26 }
 1 package com.ning;
 2 
 3 import java.util.*;
 4 
 5 public class Demo05 {
 6 
 7     public static void main(String[] args) {
 8         Set<People> set=new HashSet<People>();//创建Set集合对象
 9         set.add(new People("小别",10010));//向集合中添加元素
10         set.add(new People("小李",10011));
11         set.add(new People("小赵",10012));
12         Iterator<People> it=set.iterator();//创建集合迭代器
13         System.out.println("集合中的元素是:");
14         while(it.hasNext()){
15             People p=it.next();
16             System.out.println(p.getName()+"  "+p.getId_card());
17         }
18     }
19 
20 }
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016-10-23 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档