本文共 2397 字,大约阅读时间需要 7 分钟。
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 Listlist=new ArrayList ();//创建List集合10 list.add("b");//将List集合中添加元素11 list.add("a");12 list.add("c");13 list.add("q");14 list.add("c");15 Set set=new HashSet ();//创建List集合对象16 set.addAll(list);//将List集合添加到Set集合中17 set.add("111");18 set.remove("111");19 Iterator 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 Setset=new HashSet ();//创建Set集合对象 9 set.add(new People("小别",10010));//向集合中添加元素10 set.add(new People("小李",10011));11 set.add(new People("小赵",10012));12 Iterator 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 }
转载地址:http://qfocl.baihongyu.com/