Set接口的实现类常用的有HashSet和TreeSet类。
Set<String> collSet = new HashSet<String>();
Set<String> collSet2 = new TreeSet<String>();
由于Set集合中的对象是无序的,遍历Set集合的结果与插入Set集合的顺序并不相同。
例:遍历输出HashSet中的全部元素。
(1)创建People对象,该对象中包含有String类型和long类型属性,并包含有属性的setXXX()与getXXX()方法。代码如下:
package test;
import java.util.*;
class People{
private String name;
private long id_card;
public People(String name,long id_card){
this.name = name;
this.id_card = id_card;
}
public long getId_card(){
return id_card;
}
public String getName(){
return name;
}
}
public class Main{
public static void main(String []args){
Set<People> hashSet = new HashSet<People>();
hashSet.add(new People("陈同学",201101));
hashSet.add(new People("王同学",201102));
hashSet.add(new People("李同学",201103));
Iterator<People> it = hashSet.iterator();
System.out.println("集合中的元素是:");
while(it.hasNext()){
People person = it.next();
System.out.println(person.getName()+" "+person.getId_card());
}
}
}