通过单次查找初始化 Java Map 中的条目(就像在 C++ 中一样)
在 C++ 中,我可以在映射中查找键,如果不存在则将其插入,只需一次查找的成本。我可以在 Java 中做同样的事情吗?
更新:(
对于那些必须查看代码的人。)
long id = 0xabba;
int version = 0xb00b;
for (List<Object> key : keys) {
if (!index.containsKey(key)) {
index.put(key, Maps.<Long,Integer>newHashMap());
}
index.get(key).put(id, version);
}
当密钥首次插入映射时,有两次查找。在 C++ 中,我可以通过一次查找来完成。
In C++, I can look up a key in a map and insert it if it's not there for the cost of a single look up. Can I do the same in Java?
Update:
(For those of you who must see code.)
long id = 0xabba;
int version = 0xb00b;
for (List<Object> key : keys) {
if (!index.containsKey(key)) {
index.put(key, Maps.<Long,Integer>newHashMap());
}
index.get(key).put(id, version);
}
There are two look ups when the key is first inserted into the map. In C++, I could do it with a single look up.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
并发映射具有原子
putIfAbsent
方法,如果这就是您的意思。Concurrent maps have an atomic
putIfAbsent
method, if this is what you mean.我并不完全熟悉 C++ 内在实现,但我对它在性能/效率方面是否是单个操作有一些疑问。
即使是这样,为什么你一定需要 Java 中的一个呢?或者甚至想要一个?
假设它看起来像这样:
lookup(object) // sideeffect of object insert
除了并发之外,我不希望在 Java 中使用类似的东西。
编辑:澄清
I am not entirely familiar with C++ intrinsic implementation, but I have some doubts about it being a single operation in terms of performance/efficiency.
Even if it was, why would you necessarily need one in Java? Or even want one?
Assuming that it looks something like:
lookup(object) // side effect of object insertion
I wouldn't want something like this in Java for anything other than concurrency.
EDIT: clarification