Skip to content
Permalink
Browse files

8238684: Override getOrDefault in immutable Map implementation

Reviewed-by: forax, psandoz, smarks
  • Loading branch information
cl4es committed Feb 8, 2020
1 parent 7552915 commit ac69c7894dafa684b9c61672ea57411895466e19
@@ -904,6 +904,20 @@ private Object writeReplace() {
@Override public V replace(K key, V value) { throw uoe(); }
@Override public boolean replace(K key, V oldValue, V newValue) { throw uoe(); }
@Override public void replaceAll(BiFunction<? super K,? super V,? extends V> f) { throw uoe(); }

/**
* @implNote {@code null} values are disallowed in these immutable maps,
* so we can improve upon the default implementation since a
* {@code null} return from {@code get(key)} always means the default
* value should be returned.
*/
@Override
public V getOrDefault(Object key, V defaultValue) {
V v;
return ((v = get(key)) != null)
? v
: defaultValue;
}
}

static final class Map1<K,V> extends AbstractImmutableMap<K,V> {
@@ -34,6 +34,9 @@
*/
@State(Scope.Benchmark)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
@Fork(value = 3)
@Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 5, time = 2, timeUnit = TimeUnit.SECONDS)
public class ImmutableColls {

public static String[] STRINGS = {"hi", "all", "of", "you"};
@@ -217,6 +220,13 @@ public boolean containsValueFinalMap() {
fm4.containsValue("hi");
}

@Benchmark
@CompilerControl(CompilerControl.Mode.DONT_INLINE)
public void getOrDefault(Blackhole bh) {
bh.consume(fm4.getOrDefault("hi", "test"));
bh.consume(fm4.getOrDefault("not_in_this_map", "test"));
}

public int sizeOf(List<String> list) {
return list.size();
}

0 comments on commit ac69c78

Please sign in to comment.