集合是一个集合,不能包含重复的元素。它为数学集合抽象建模。
Set接口仅包含从Collection继承的方法,并增加了禁止重复元素的限制。
Set还为equals和hashCode操作的行为增加了更紧密的约定,从而即使它们的实现类型不同,也可以有意义地比较Set实例。
下表总结了Set声明的方法-序号方法与说明
1加()
将对象添加到集合中。
2清除()
从集合中删除所有对象。
3contains()
如果指定对象是集合中的元素,则返回true。
4是空的( )
如果集合没有元素,则返回true。
5迭代器()
返回集合的Iterator对象,该对象可用于检索对象。
6去掉( )
从集合中删除指定的对象。
7尺寸()
返回集合中的元素数。
Set在各种类(例如HashSet,TreeSet,LinkedHashSet)中都有其实现。以下是解释Set功能的示例-
示例
import java.util.*;
public class SetDemo {
public static void main(String args[]) {
int count[] = {34, 22,10,60,30,22};
Set set = new HashSet();
try {
for(int i = 0; i
set.add(count[i]);
}
System.out.println(set);
TreeSet sortedSet = new TreeSet(set);
System.out.println("The sorted list is:");
System.out.println(sortedSet);
System.out.println("The First element of the set is: "+ (Integer)sortedSet.first());
System.out.println("The last element of the set is: "+ (Integer)sortedSet.last());
}
catch(Exception e) {}
}
}
这将产生以下结果-
输出结果[34, 22, 10, 60, 30]
The sorted list is:
[10, 22, 30, 34, 60]
The First element of the set is: 10
The last element of the set is: 60