Java中HashMap和HashSet的區別。


HashMapHashSet 都是 Java集合框架 中最重要的類之一。

以下是HashMap和HashSet之間的一些重要區別。

序號關鍵點HashMapHashSet
1實現HashMap是Map介面的實現。HashSet是Set介面的實現。
2內部實現HashMap在內部並沒有實現HashSet或任何Set來進行實現。HashSet在內部使用HashMap來實現。
3元素儲存HashMap以鍵值對的形式儲存元素,即每個元素都有其對應的鍵,在迭代過程中需要使用鍵進行檢索。HashSet只儲存物件,不維護鍵值對。
4新增元素的方法HashMap的put方法用於向HashMap中新增元素。HashSet的add方法用於向HashSet中新增元素。
5索引效能由於HashMap具有唯一的鍵,因此在迭代過程中檢索元素的速度更快。HashSet完全基於物件,因此與HashMap相比速度較慢。
6允許空值HashMap可以插入單個空鍵和任意數量的空值,沒有任何限制。HashSet在其集合中只允許一個空值,之後不允許新增任何空值。

HashMap與HashSet示例

JavaTester.java

 線上演示

import java.util.HashSet;
public class JavaTester {
   public static void main(String[] args){
      HashSet<String> hs = new HashSet<String>();
      hs.add("John");
      hs.add("Smith");
      hs.add("Peter");
      System.out.println("Before adding duplicate values 

"
+ hs);       hs.add("John");       hs.add("Smith");       System.out.println("
After adding duplicate values

"
+ hs);       hs.add(null);       hs.add(null);       System.out.println("
After adding null values

"
+ hs);    } }

輸出

Before adding duplicate values
[John, Smith, Peter]
After adding duplicate values
[John, Smith, Peter]
After adding null values
[null, John, Smith, Peter]

示例

JavaTester.java

 線上演示

import java.util.HashMap;
public class JavaTester {
   public static void main(String[] args){
      HashMap<Integer, String> hm = new HashMap<Integer, String>();
      hm.put(12, "John");
      hm.put(2, "Smith");
      hm.put(7, "Peter");
      System.out.println("
HashMap object output :

"
+ hm);       hm.put(12, "Smith");       System.out.println("
After inserting duplicate key :

"
+ hm);    } }

輸出

HashMap object output :
{2=Smith, 7=Peter, 12=John}
After inserting duplicate key :
{2=Smith, 7=Peter, 12=John}

更新於:2023年9月15日

24K+瀏覽量

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告