教程 > Java 教程 > Java 高级 阅读:16

Java Set 接口

返回 Java 集合框架


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

返回 Java 集合框架

查看笔记

扫码一下
查看教程更方便