为什么LinkedHashMap不提供按索引的访问? [英] Why doesn't LinkedHashMap provide access by index?

查看:88
本文介绍了为什么LinkedHashMap不提供按索引的访问?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自Javadoc:
Map接口的哈希表和链表实现,具有可预测的迭代顺序.此实现与HashMap的不同之处在于,它维护贯穿其所有条目的双向链接列表.

From Javadoc:
Hash table and linked list implementation of the Map interface, with predictable iteration order. This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries.

如果是这样,那么为什么它不提供像Java中的List这样的对象访问权限,list.get(index);

If it is so, then why doesn't it provide object access like List in java, list.get(index);

更新

我已经使用LinkedHashMap实现了LRU Cache.我的算法要求我从缓存访问LRU对象.这就是为什么我需要随机访问的原因,但是我认为这会降低性能,因此我更改了逻辑,仅在缓存已满时才访问LRU对象...使用removeEldestEntry()

I had implemented LRU Cache using LinkedHashMap. My algorithm required me to access LRU Object from the cache. That's why I required random access, but I think that will cost me bad performance, so I have changed the logic and I am accessing the LRU object just when Cache is full...using removeEldestEntry()

谢谢大家...

推荐答案

a)因为条目是链接的,所以不能随机访问.如果我没记错的话,性能会很糟糕, O(N).

a) Because the entries are linked, not randomly accessible. The performance would be miserable, O(N) if I'm not in error.

b),因为没有用于备份此功能的界面.因此,选择要么为此操作(性能很差)引入专用接口,要么要求客户端针对实现类而不是接口进行编程

b) Because there is no interface to back up this functionality. So the choice would be to either introduce a dedicated interface just for this (badly performing) Implementation or require clients to program against implementation classes instead of interfaces

使用 Guava 顺便说一句,为您提供了一个简单的解决方案:

Btw with Guava there's a simple solution for you:

Iterables.get(map.values(), offset);

要进行缓存,请查看Guava的

And for caching look at Guava's MapMaker and it's expiration features.

这篇关于为什么LinkedHashMap不提供按索引的访问?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆