当我开始使用它们时,我使用了它们中的任何一个,而不管它们之间的差异。后来我发现它们之间存在明显的差异,这会影响你的应用程序的性能。.在我们真正看到差异之前,让我给你简单介绍一下两者。
HashMap实现 了Map 接口,该接口将键映射到值。它不是同步的,也不是线程安全的。不允许重复键,并且允许空键和值。
HashMap<Interger,String> employeeHashmap=new HashMap<Integer,String>(); employeeHashmap.put(1,"Arpit"); employeeHashmap.put(2,null); // will work fine
Hashtable 实现了 Map接口,将键映射到值。它是同步的和线程安全的。不允许重复键,也不允许空键。
Hashtable<Interger,String> employeeHashmap=new Hashtable<Integer,String>(); employeeHashmap.put(1,"Arpit"); employeeHashmap.put(2,null); //not allowed and will throw NullPointer exception at run time
一些重要的问题需要讨论。
是的,我们也可以在 Collections.synchonizedMap(hashmap) 的帮助下同步 HashMap,因此 HashMap 可以通过
Map map=Collections.synchonizedMap(hashmap)
原文链接:https://codingdict.com/