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


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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM