Java 中的 LinkedHashMap 收缩
如何缩小LinkedHashMap
?我重写了 removeEldestEntry
方法,但该方法仅在插入新值时调用一次。因此,以这种方式缩小地图并没有改变。
LinkedHashMap
只给了我一个普通的 Iterator
并且没有任何 removeLast
或 listIterator
方法,那么如何才能您找到最后的(例如 1000 个)条目并将其删除吗?
我能想到的唯一方法就是迭代整个事情。但这可能需要很长时间......
每次我只想删除一些元素时创建一个新地图也会破坏内存。
当 removeEldestEntry
方法中的 maxSize
减小时,可能会删除 Iterator
的第一个值,然后重新插入它们。然后重新插入会剔除最旧的值。这是非常丑陋的代码......还有更好的想法吗?
编辑:抱歉,迭代顺序是从最旧到最年轻的。所以这很容易
How can you shrink a LinkedHashMap
? I overrode the removeEldestEntry
method, but this method is only called once when a new value is inserted. So there is no change of making the map smaller this way.
The LinkedHashMap
only gives my a normal Iterator
and doesn't have any removeLast
or listIterator
method, so how can you find the last, say 1000, entries and remove them?
The only way I can think of is iterating through that whole thing. But that can take ages...
Creating a new map every time I want to remove only a few elements will also destroy the memory.
Maybe remove the first values of the Iterator
and then reinserted them, when the maxSize
was reduced in the removeEldestEntry
method. Then the reinserting would kick out the oldest values. This is very ugly code... Any better ideas?
EDIT: Sry the iteration order is oldest to youngest. So it's easy
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
迭代器将从最旧的到最年轻的 LinekdHashMap 进行迭代。如果您想将 LinkedHashMap 缩小到可以使用以下内容的大小。
每个删除条目大约需要 20 ns。
The iterator will iterate from oldest to youngest for LinekdHashMap. You if you want to shrink the LinkedHashMap to a size you can use the following.
This should take about 20 ns per entry removed.
LRU缓存使用LinkedHashMap(访问有序)实现。这还通过注册/订阅此类事件的调用者通知回调的返回值来动态执行收缩和扩展。
代码有很好的注释来详细说明实现。
使用此 LRU 缓存实现的测试类:
LRU cache Implementation which uses LinkedHashMap(access ordered). This also performs shrink and expand on the fly via a return value from the caller's notification callback registered/subscribed to this class's events.
Code is pretty well commented to detail the implementation.
Testing class which uses this LRU Cache implementation: