Java 数据结构 - Set 接口
Set 是一个无序的集合,不允许重复元素。它模拟了数学集合的抽象。当我们向其中添加元素时,它会动态增长。Set 类似于数组。
Set 接口
Set 是一个不能包含重复元素的集合。它模拟了数学集合的抽象。
Set 接口仅包含从 Collection 继承的方法,并添加了不允许重复元素的限制。
Set 还对 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 等各种类中都有实现。以下是一个解释 Set 功能的示例:
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) {}
}
}
输出
[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
广告