Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 9488578

Browse files
putIfAbsent + doc update
1 parent 29b3777 commit 9488578

File tree

2 files changed

+54
-1
lines changed

2 files changed

+54
-1
lines changed

‎README.md‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,9 @@ In `Map.Entry`:
5252
* `default V putIfAbsent(K key, V value)`- If the specified key is
5353
not already associated with a value (or is mapped to null) associates
5454
it with the given value and returns null, else returns the current value.
55+
56+
_Remark_: `map.putIfAbsent(1, null);` is OK
57+
5558
* `default boolean remove(Object key, Object value)`
5659
* `default void replaceAll(BiFunction<? super K, ? super V, ? extends V> function)`
5760
* `default boolean replace(K key, V oldValue, V newValue)`
@@ -90,4 +93,10 @@ We provide tests for above mentioned methods.
9093
```
9194
map.getOrDefault(1, "NOT-FOUND");
9295
```
93-
1. modifying
96+
1. modifying
97+
* putIfAbsent - good way of initializing entries in map
98+
```
99+
Map<String, Integer> counter = new HashMap<>();
100+
101+
counter.putIfAbsent("11-u", 0);
102+
```

‎src/test/java/MapModifyingTest.java‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
import org.junit.Test;
2+
3+
import java.util.HashMap;
4+
import java.util.Map;
5+
6+
import static org.hamcrest.CoreMatchers.is;
7+
import static org.hamcrest.MatcherAssert.assertThat;
8+
9+
/**
10+
* Created by mtumilowicz on 2018年11月09日.
11+
*/
12+
public class MapModifyingTest {
13+
14+
@Test
15+
public void putIfAbsent_exists() {
16+
Map<Integer, String> map = new HashMap<>();
17+
18+
map.put(1, "1");
19+
20+
map.putIfAbsent(1, "2");
21+
22+
assertThat(map.get(1), is("1"));
23+
}
24+
25+
@Test
26+
public void putIfAbsent_notExists() {
27+
Map<Integer, String> map = new HashMap<>();
28+
29+
map.putIfAbsent(1, "1");
30+
31+
assertThat(map.get(1), is("1"));
32+
}
33+
34+
@Test
35+
public void putIfAbsent_mappedToNull() {
36+
Map<Integer, String> map = new HashMap<>();
37+
38+
map.put(1, null);
39+
40+
map.putIfAbsent(1, "1");
41+
42+
assertThat(map.get(1), is("1"));
43+
}
44+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /