修剪 HashMap 的有效方法
我正在用 Java 创建 Flyweight,并且我想确保不会创建太大的地图。有没有更有效的方法来修剪地图?我没有看到任何可以自动执行此操作的属性(例如最大大小构造函数),因此我在代码中执行此操作。
这是我所拥有的,它非常基本,但我想确保没有更好的方法:
private static void prune() {
Iterator<Entry<Integer, Integer[]>> iterator = seeds.entrySet().iterator();
int removed = 0;
while(iterator.hasNext()|| removed == pruneLength) {
iterator.next();
iterator.remove();
removed++;
}
}
I am creating a Flyweight in Java, and I want to make sure I don't create too large a map. Is there a more efficient way to prune the map? I did not see any properties that could do this automatically (like a max size constructor), so I am doing it in code.
Here is what I have, its pretty basic, but I want to make sure there isn't a better way:
private static void prune() {
Iterator<Entry<Integer, Integer[]>> iterator = seeds.entrySet().iterator();
int removed = 0;
while(iterator.hasNext()|| removed == pruneLength) {
iterator.next();
iterator.remove();
removed++;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
LinkedHashMap可以用作LRU缓存。
LinkedHashMap can used as a LRU cache.
Guava 的 MapMaker 的最新版本(在主干上)中有此功能。应该是r08,虽然我不知道具体什么时候出来。
请注意,这是一个线程安全的并发映射,这看起来可能很重要,具体取决于您如何使用它。
Guava's MapMaker has this in its latest version (on trunk). It should be in r08, though I don't know when that's coming out exactly.
Note that this is a thread-safe concurrent map, which seems like it might be important depending on how you're using it.
您是否考虑过使用缓存,例如 EhCache ?它们实现映射,并以声明方式设置大小、值存储在磁盘上后的限制等。
Have you considered using caches, EhCache for example? They implement maps and declaratively you can set the size, limit after values are stored on a disk etc.
数据库世界的一种可能性是拥有两个(或可能更多的地图)。查找使用这两个映射。只写给一个。当写入的数据达到容量时,替换/清除只读映射并进行切换。
One possibility from the world of databases is to have two (or potentially more maps). Lookups use both maps. Writes to just one. When the one being written hits capacity, replace/clear the read-only map and switch.