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
廣告