Java中HashMap和HashSet的區別。
HashMap 和 HashSet 都是 Java集合框架 中最重要的類之一。
以下是HashMap和HashSet之間的一些重要區別。
| 序號 | 關鍵點 | HashMap | HashSet |
|---|---|---|---|
| 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}
廣告
資料結構
網路
關係型資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP