Reputation: 9465
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.
Upvotes: 2
Views: 497
Reputation: 12742
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
Upvotes: 0
Reputation: 116266
Concurrent maps have an atomic putIfAbsent
method, if this is what you mean.
Upvotes: 6