Fastest way to determine the lowest available key in Java HashMap?

一笑奈何 提交于 2020-08-23 08:03:59

问题


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"
}

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;
}

In some cases, this is really slow. Is there any faster or more professional way to get the lowest free key of a HashMap?


回答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.

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.



来源:https://stackoverflow.com/questions/18345131/fastest-way-to-determine-the-lowest-available-key-in-java-hashmap

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!