我想澄清一下 Java 8 中 hashtable 和 hashmap 之间的差异。
据我所知,HashTable 的功能与 HashMap 类似,但它是线程安全的,并且不允许空键或空值。我知道 Java 8 更新了 HashMap 类,这样当发生冲突时,它不会创建存储桶中具有相同哈希代码的项目的链接列表,而是创建一棵树。哈希表也是如此吗?即使在碰撞之前,树也是默认存储方法吗? (就像,当第一个放入桶中的元素被放置在那里时,它只是一个没有分支的树根。)
另外,java如何确保哈希表是线程安全的?当两个线程尝试同时访问一段数据时,它是否会创建一个队列?
最佳答案
Is this also the case with hashtable?
没有。
And is the tree the default storage method even before a collision? (As in, when the first item to fit into a bucket is placed there, it's just a tree root with no branches.)
没有。 HashMap
类有一个名为 TREEIFY_THRESHOLD
的常量。 (值 8)。
Javadoc 说“使用树而不是容器列表的容器计数阈值。当将元素添加到至少具有这么多节点的容器时,容器将转换为树”。 p>
Also, how does java ensure that a hashtable is threadsafe?
Hashtable
的 javadoc显式表示:“与新的集合实现不同,Hashtable 是同步的”。。
Does it create a que when two threads try to concurrently access a piece of data?
没有。
关于Java 8 HashTable 与 HashMap 冲突处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55405627/