java - LinkedHashMap 与 HashMap 中的删除

标签 java collections hashmap time-complexity

LinkedHashMap 中的删除需要线性时间,这是否正确?由于我们需要从保持插入顺序的链表中删除键,这将花费 O(n) 时间。在常规的 HashMap 中,删除需要恒定的时间。

最佳答案

根据Javadocs ,它不是:

This class provides all of the optional Map operations, and permits null elements. Like HashMap, it provides constant-time performance for the basic operations (add, contains and remove), assuming the hash function disperses elements properly among the buckets. Performance is likely to be just slightly below that of HashMap, due to the added expense of maintaining the linked list, with one exception: Iteration over the collection-views of a LinkedHashMap requires time proportional to the size of the map, regardless of its capacity. Iteration over a HashMap is likely to be more expensive, requiring time proportional to its capacity.

LinkedHashMap不会覆盖HashMap#remove(Object key)方法。后者从表中删除与该键对应的条目并调用 recordRemoval()已删除条目上的方法,该方法调整已删除条目的上一个和下一个链接。列表中没有为了删除某个索引处的节点而进行的迭代。

关于java - LinkedHashMap 与 HashMap 中的删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29377949/

相关文章:

java - 如何让我的程序只运行第二个输出?

java - 获取菜单项以(取消)检查它

java - 使用java从liferay cms检索内容

java - 用于初始化依赖于另一个应用程序 EJB 的 EJB 的模式

c# - 我如何(快速)在 C#/.Net 中找到最长的匹配字符串

java - 为什么无效的 compareTo 不会导致 Collections.sort 崩溃?

java - 如何以在 11 之前对 2 进行排序的方式使用 java 的排序函数?

Java HashMap 先按值再按键排序

java - 如何在不覆盖之前数据的情况下使用 hashmap.put? ( java )

java - 为什么哈希集解决方案被接受,而使用 HashMap 却出现超时错误-在数组中查找具有差异 K 的对?