Java 的 Set 中可以新增 null 元素嗎?
Set 是一種不能包含重複元素的集合。它模擬了數學集合的抽象概念。
它不允許重複元素,最多允許一個 null 值。
Set 還對 equals 和 hashCode 操作的行為增加了更嚴格的約定,允許即使實現型別不同也能有意義地比較 Set 例項。
有三個類實現了這個介面:
- HashSet − 基於雜湊表的 Set 實現。
- LinkedHashSet − 基於連結串列的 HashSet 實現。
- TreeSet − 基於樹的 Set 實現。
Set 物件中的 null 值
根據定義,Set 物件不允許重複值,但它最多允許一個 null 值。
HashSet 中的 null 值 − HashSet 物件允許 null 值,但是你只能向其中新增一個 null 元素。即使你添加了多個 null 值,如果嘗試列印其內容,它也只會顯示一個 null。
示例
import java.util.HashSet; import java.util.Set; public class HashSetExample { public static void main(String args[]) { Set<Integer> hashSet = new HashSet<Integer>(); //Populating the HashSet hashSet.add(1124); hashSet.add(3654); hashSet.add(7854); hashSet.add(9945); System.out.println(hashSet); //Adding null elements hashSet.add(null); hashSet.add(null); hashSet.add(null); System.out.println(hashSet); } }
輸出
[1124, 3654, 9945, 7854] [null, 1124, 3654, 9945, 7854]
LinkedHashSet 中的 null 值:與 HashSet 物件一樣,它也允許 null 值,但是你只能向其中新增一個 null 元素。即使你添加了多個 null 值,如果嘗試列印其內容,它也只會顯示一個 null。
示例
import java.util.LinkedHashSet; import java.util.Set; public class LinkedHashSetExample { public static void main(String args[]) { Set<Integer> linkedHashSet = new LinkedHashSet<Integer>(); //Populating the HashSet linkedHashSet.add(1124); linkedHashSet.add(3654); linkedHashSet.add(7854); linkedHashSet.add(9945); System.out.println(linkedHashSet); //Adding null elements linkedHashSet.add(null); linkedHashSet.add(null); linkedHashSet.add(null); System.out.println(linkedHashSet); } }
輸出
[1124, 3654, 9945, 7854] [null, 1124, 3654, 9945, 7854]
TreeSet 中的 null 值 − TreeSet 物件不允許 null 值。如果你嘗試新增它們,將會丟擲執行時異常。
示例
import java.util.Set; import java.util.TreeSet; public class TreeSetExample { public static void main(String args[]) { Set<Integer> treeSet = new TreeSet<Integer>(); //Populating the HashSet treeSet.add(1124); treeSet.add(3654); treeSet.add(7854); treeSet.add(9945); System.out.println(treeSet); //Adding null elements treeSet.add(null); treeSet.add(null); treeSet.add(null); System.out.println(treeSet); } }
執行時異常
[1124, 3654, 7854, 9945] Exception in thread "main" java.lang.NullPointerException at java.util.TreeMap.put(Unknown Source) at java.util.TreeSet.add(Unknown Source) at MyPackage.TreeSetExample.main(TreeSetExample.java:16)
廣告