转自 https://www.cnblogs.com/xiaxj/p/7891963.html
Set集合的特点:不能存储相同的元素。同时因为其是一个抽象的接口:所以不能直接实例化一个set对象。(Set s = new Set() )错误。该接口主要继承于Collections接口,所以具有Collection的一些常见的方法。
常见的方法:
add( ) 向集合中添加元素
clear( ) 去掉集合中所有的元素
contains( ) 判断集合中是否包含某一个元素
isEmpty( ) 判断集合是否为空
iterator( ) 主要用于递归集合,返回一个Iterator()对象
remove( ) 从集合中去掉特定的对象
size( ) 返回集合的大小
Set接口最长用的两大实现:HashSet TreeSet
TreeSet:会将里面的元素默认排序
。
Set<Integer> test = new TreeSet<>();
int a = 1;
int b = 8;
int c = 3;
test.add(a);
test.add(b);
test.add(c);
//遍历集合test 利用foreach遍历 //输出结果:1 3 8
for (Integer value : test) {
System.out.print(value+" ");
}
//利用Iterator实现遍历
Iterator<Integer> value = test.iterator();
while (value.hasNext()) {
int s = value.next();
System.out.print(s+" ");
} //输出结果:1 3 8