Java 中 HashMap 和 Hashtable 的差異
Hashtable 是 java.util 的一部分,是 Dictionary 的具體實現。但是,Java 2 重新設計了 Hashtable,使其也實現了 Map 介面。因此,Hashtable 現在已整合到集合框架中。它與 HashMap 類似,但已同步。
與 HashMap 一樣,Hashtable 在雜湊表中儲存鍵/值對。使用 Hashtable 時,指定一個用作鍵的物件以及希望連結到該鍵的值。然後對鍵進行雜湊處理,並將所得雜湊程式碼用作在表中儲存該值時的索引。
HashMap 類是基於雜湊表的 Map 介面的實現。
- 該類不保證對映的迭代順序;特別是,它不保證該順序在一段時間內保持不變。
- 該類允許空值和空鍵。
示例
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class HashMap_HashTable {
public static void main(String args[]) {
// Create a hash map
HashMap hm = new HashMap();
// Put elements to the map
hm.put("Zara", new Double(3434.34));
hm.put("Mahnaz", new Double(123.22));
hm.put("Ayan", new Double(1378.00));
hm.put("Daisy", new Double(99.22));
hm.put("Qadir", new Double(-19.08));
// Get a set of the entries
Set set = hm.entrySet();
// Get an iterator
Iterator i = set.iterator();
// Display elements
while(i.hasNext()) {
Map.Entry me = (Map.Entry)i.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
System.out.println();
// Deposit 1000 into Zara's account
double balance = ((Double)hm.get("Zara")).doubleValue();
hm.put("Zara", new Double(balance + 1000));
System.out.println("Zara's new balance: " + hm.get("Zara"));
HashMap< String, String> hMap = new HashMap< String, String>();
hMap.put("1", "1st");
hMap.put("2", "2nd");
hMap.put("3", "3rd");
Collection cl = hMap.values();
Iterator itr = cl.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
}
}輸出
Daisy: 99.22 Ayan: 1378.0 Zara: 3434.34 Qadir: -19.08 Mahnaz: 123.22 Zara's new balance: 4434.34 1st 2nd 3rd
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP