[英]Initialize entry in Java Map with single look up (like in 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. 在C ++中,我可以在映射中查找键并将其插入(如果键不存在的话),这需要一次查找。 Can I do the same in Java? 我可以在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. 在C ++中,我可以通过一次查找来实现。
如果这是您的意思,则并发映射具有原子的putIfAbsent
方法。
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. 我对C ++内在实现并不完全熟悉,但是就性能/效率而言,我对它是一个单一的操作还是有些疑问。
Even if it was, why would you necessarily need one in Java? 即使是这样,为什么您一定需要用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. 除了并发之外,我不想在Java中使用类似的东西。
EDIT: clarification 编辑:澄清
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.