Java中HashMap和Hashtable之间的区别是什么?
对于非线程应用程序,哪个更有效?
Java中HashMap和Hashtable之间的区别是什么?
对于非线程应用程序,哪个更有效?
当前回答
hashtable和hashmap之间的另一个关键区别是,hashmap中的Iterator是快速失败的,而hashtable的枚举器不是快速失败的。如果任何其他线程通过添加或删除Iterator自己的remove()方法以外的任何元素来从结构上修改映射,则抛出ConcurrentModificationException。但这不是一种保证的行为,将由JVM尽最大努力完成。"
我的来源:http://javarevisited.blogspot.com/2010/10/difference-between-hashmap-and.html
其他回答
哈希表:
Hashtable是一种保留键值对值的数据结构。它不允许键和值都为null。如果添加null值,将获得NullPointerException。它是同步的。因此,它有其成本。在特定时间,只有一个线程可以访问HashTable。
例子:
import java.util.Map;
import java.util.Hashtable;
public class TestClass {
public static void main(String args[ ]) {
Map<Integer,String> states= new Hashtable<Integer,String>();
states.put(1, "INDIA");
states.put(2, "USA");
states.put(3, null); //will throw NullPointerEcxeption at runtime
System.out.println(states.get(1));
System.out.println(states.get(2));
// System.out.println(states.get(3));
}
}
哈希映射:
HashMap类似于Hashtable,但它也接受键值对。它允许键和值都为空。它的性能优于HashTable,因为它是非同步的。
例子:
import java.util.HashMap;
import java.util.Map;
public class TestClass {
public static void main(String args[ ]) {
Map<Integer,String> states = new HashMap<Integer,String>();
states.put(1, "INDIA");
states.put(2, "USA");
states.put(3, null); // Okay
states.put(null,"UK");
System.out.println(states.get(1));
System.out.println(states.get(2));
System.out.println(states.get(3));
}
}
hashtable和hashmap之间的另一个关键区别是,hashmap中的Iterator是快速失败的,而hashtable的枚举器不是快速失败的。如果任何其他线程通过添加或删除Iterator自己的remove()方法以外的任何元素来从结构上修改映射,则抛出ConcurrentModificationException。但这不是一种保证的行为,将由JVM尽最大努力完成。"
我的来源:http://javarevisited.blogspot.com/2010/10/difference-between-hashmap-and.html
1.Hashmap和HashTable都存储键和值。
2.Hashmap可以将一个键存储为null。哈希表不能存储null。
3.HashMap未同步,但Hashtable已同步。
4.HashMap可以与Collection.SyncronizedMap(map)同步
Map hashmap = new HashMap();
Map map = Collections.SyncronizedMap(hashmap);
HashMap:使用哈希代码对数组进行索引的Map接口的实现。哈希表:嗨,1998年来电话。他们想拿回他们的集合API。
说真的,你最好完全远离Hashtable。对于单线程应用程序,您不需要额外的同步开销。对于高度并发的应用程序,偏执的同步可能会导致饥饿、死锁或不必要的垃圾收集暂停。正如Tim Howland所指出的,您可以使用ConcurrentHashMap。
HashMap是模拟的,因此可以在GWT客户端代码中使用,而Hashtable不是。