Java Set 接口
Set集合不能包含重复的元素的集合。该模型数学抽象集合。
Set接口只包含继承自Collection的方法,并增加了重复的元素被禁止约束性。
集还增加了对equals和hashCode操作的行为更强的契约,允许Set集合实例进行有意义的比较,即使他们的实现类型不同。
通过Set集声明的方法总结如下表:
| 序号 | 方法描述 |
|---|---|
| 1 | add( ) 将对象添加到集合。 |
| 2 | clear( ) 从集合中移除所有对象。 |
| 3 | contains( ) 如果指定的对象是集合中的元素返回true。 |
| 4 | isEmpty( ) 如果集合不包含任何元素,则返回true。 |
| 5 | iterator( ) 返回一个Iterator对象,可用于检索对象的集合。 |
| 6 | remove( ) 从集合中删除指定的对象。 |
| 7 | size( ) 返回元素集合中的数。 |
实例
Set 集有其不同的类,如HashSet,TreeSet,LinkedHashSet 实现。以下为例子来说明集功能:
import java.util.*;
public class SetDemo {
public static void main(String args[]) {
int count[] = {34, 22,10,60,30,22};
Set<Integer> set = new HashSet<Integer>();
try{
for(int i = 0; i<5; i++){
set.add(count[i]);
}
System.out.println(set);
TreeSet sortedSet = new TreeSet<Integer>(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){}
}
}
以上实例编译运行结果如下:
[amrood]$ java SetDemo [34, 30, 60, 10, 22] 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

国外主机测评 - 国外VPS,国外服务器,国外云服务器,测评及优惠码













