Java中的HashMap和HashTable有什么区别
HashMap和HashTable都是JavaCollection框架最重要的类之一。HashMap和HashTable都将数据存储在键值对中,并且在存储数据时使用哈希对键进行哈希处理,并将生成的哈希码用作将值存储在表中的索引。但是,这两个类之间仍有许多差异,我们将在下面讨论。
以下是HashMap和HashTable之间的重要区别。
HashMap与HashTable的示例
JavaTester.java
import java.util.*;
import java.lang.*;
import java.io.*;
public class JavaTester{
public static void main(String args[]){
Hashtable ht=new Hashtable();
ht.put(101,"John");
ht.put(101,"Jhony");
ht.put(102,"Smith");
ht.put(103,"Andy");
System.out.println("-------------Hash table--------------");
Set<Integer> keySet = ht.keySet();
for (Integer key:keySet) {
System.out.println(key + " "+ht.get(key));
}
HashMap hm=new HashMap();
hm.put(100,"John");
hm.put(104,"John"); // hash map allows duplicate values
hm.put(101,"Smith");
hm.put(102,"Andy");
System.out.println("-----------Hash map-----------");
Set<Integer> keySet1 = ht.keySet();
for (Integer key:keySet) {
System.out.println(key + " "+hm.get(key));
}
}
}输出结果
-------------Hash table-------------- 103 Andy 102 Smith 101 Jhony -----------Hash map----------- 100 John 101 Smith 102 Andy 104 John