开发者

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. Can I do the same in Java?

Update:

(For those of 开发者_StackOverflowyou 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.


Concurrent maps have an atomic putIfAbsent method, if this is what you mean.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜