问题描述
想象一下这样的情况:我有一个HashMap<Integer, String>
,用于存储连接的客户端.它是HashMap
,因为顺序无关紧要,我需要速度.看起来像这样:
Imagine a situation like this:I have a HashMap<Integer, String>
, in which I store the connected clients. It is HashMap
, because the order does not matter and I need speed. It looks like this:
{
3: "John",
528: "Bob",
712: "Sue"
}
大多数客户端都断开连接,因此这就是我有很大差距的原因.如果要添加新客户端,则需要密钥,显然使用_map.size()
来获取密钥是不正确的.
Most of the clients disconnected, so this is why I have the large gap.If I want to add a new client, I need a key and obviously the usage of _map.size()
to get a key is incorrect.
因此,当前,我使用此功能来获取最低可用密钥:
So, currently I use this function to get he lowest available key:
private int lowestAvailableKey(HashMap<?, ?> _map) {
if (_map.isEmpty() == false) {
for (int i = 0; i <= _map.size(); i++) {
if (_map.containsKey(i) == false) {
return i;
}
}
}
return 0;
}
在某些情况下,这确实很慢.是否有更快或更专业的方法来获取HashMap
的最低可用密钥?
In some cases, this is really slow.Is there any faster or more professional way to get the lowest free key of a HashMap
?
推荐答案
是否有使用HashMap
的理由?如果您使用的是 TreeMap
,地图将通过按键自动排序.是的,您最终获得的是O(log n)而不是O(1)的访问权限,但这是最明显的方法.
Any reason to use a HashMap
? If you used TreeMap
instead, the map would be ordered by key automatically. Yes, you end up with O(log n) access instead of O(1), but it's the most obvious approach.
当然,您始终可以同时维护HashMap
和 TreeSet
,如果确实需要,请确保同时添加条目和从条目中删除条目. TreeSet
只是充当地图的有序键集.
Of course you could always maintain both a HashMap
and a TreeSet
, making sure you add entries and remove entries from both together, if you really needed to. The TreeSet
would just act as an ordered set of keys for the map.
这篇关于确定Java HashMap中最低可用密钥的最快方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!