|
25 | 25 | import java.util.NoSuchElementException; |
26 | 26 | import java.util.Objects; |
27 | 27 | import java.util.Set; |
28 | | -import java.util.function.Supplier; |
29 | 28 |
|
30 | 29 | import org.eclipse.jdt.annotation.NonNull; |
31 | 30 |
|
|
41 | 40 | */ |
42 | 41 | final class MapValueSet<T, V> implements Set<T> { |
43 | 42 | private final Map<T, V> map; |
44 | | - private final Supplier<@NonNull V> valueSupplier; |
| 43 | + private final ValueSupplier<@NonNull V> valueSupplier; |
45 | 44 | private final V removedSentinel; |
46 | 45 |
|
47 | 46 | @SuppressWarnings("unchecked") |
48 | | - MapValueSet(Map<? extends T, V> map, Supplier<@NonNull V> valueSupplier, V removedSentinel) { |
| 47 | + MapValueSet(Map<? extends T, V> map, ValueSupplier<@NonNull V> valueSupplier, V removedSentinel) { |
49 | 48 | this.valueSupplier = Objects.requireNonNull(valueSupplier); |
50 | 49 | this.removedSentinel = removedSentinel; |
51 | 50 | this.map = (Map<T, V>) map; |
52 | 51 | } |
53 | 52 |
|
| 53 | + @FunctionalInterface |
| 54 | + interface ValueSupplier<V> { |
| 55 | + V supplyValue(); |
| 56 | + } |
| 57 | + |
54 | 58 | /** |
55 | 59 | * Marks the given element as "removed"; this may actually add an element to the underlying map. |
56 | 60 | * <p> |
@@ -83,7 +87,7 @@ public void markAllRemoved() { |
83 | 87 | } |
84 | 88 |
|
85 | 89 | private @NonNull V getValue() { |
86 | | - return Objects.requireNonNull(valueSupplier.get()); |
| 90 | + return Objects.requireNonNull(valueSupplier.supplyValue()); |
87 | 91 | } |
88 | 92 |
|
89 | 93 | @Override |
@@ -220,22 +224,26 @@ public <E> E[] toArray(E[] a) { |
220 | 224 | * |
221 | 225 | * @param e The entry to update. |
222 | 226 | */ |
223 | | - public void update(T e) { |
224 | | - map.computeIfPresent(e, (k, v) -> getValue()); |
| 227 | + public boolean update(T e) { |
| 228 | + if (map.containsKey(e)) { |
| 229 | + map.put(e, getValue()); |
| 230 | + return true; |
| 231 | + } else { |
| 232 | + return false; |
| 233 | + } |
225 | 234 | } |
226 | 235 |
|
227 | 236 | /** |
228 | 237 | * Adds an entry to the set, adding it to the backing map if necessary. |
229 | 238 | */ |
230 | 239 | @Override |
231 | 240 | public boolean add(T e) { |
232 | | - if (!map.containsKey(e)) { |
233 | | - map.computeIfAbsent(e, (k) -> getValue()); |
234 | | - return true; |
235 | | - } else if (contains(e)) { |
| 241 | + if (contains(e)) { |
236 | 242 | return false; |
| 243 | + } else if (update(e)) { |
| 244 | + return true; |
237 | 245 | } else { |
238 | | - update(e); |
| 246 | + map.put(e, getValue()); |
239 | 247 | return true; |
240 | 248 | } |
241 | 249 | } |
|
0 commit comments