Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changes/next-release/bugfix-AWSSDKforJavav2-01696b7.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"type": "bugfix",
"category": "AWS SDK for Java v2",
"contributor": "",
"description": "Log error instead of throwing error for duplicate keys in ImmutableMap"
}
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,8 @@
@SdkProtectedApi
public final class ImmutableMap<K, V> implements Map<K, V> {

private static final Logger log = Logger.loggerFor(ImmutableMap.class);
private static final String UNMODIFIABLE_MESSAGE = "This is an immutable map.";
private static final String DUPLICATED_KEY_MESSAGE = "Duplicate keys are provided.";

private final Map<K, V> map;

Expand Down Expand Up @@ -199,7 +199,9 @@ public static <K, V> ImmutableMap<K, V> of(K k0, V v0, K k1, V v1,
private static <K, V> void putAndWarnDuplicateKeys(Map<K, V> map, K key,
V value) {
if (map.containsKey(key)) {
throw new IllegalArgumentException(DUPLICATED_KEY_MESSAGE);
log.error(() -> String.format("Duplicate keys are provided for [%s]. The first value [%s] will be kept, and the "
Comment thread
davidh44 marked this conversation as resolved.
Outdated
+ "second value [%s] will be ignored.", key, map.get(key), value));
return;
}
map.put(key, value);
}
Expand Down Expand Up @@ -295,9 +297,8 @@ public Builder() {
}

/**
* Add a key-value pair into the built map. The method will throw
* IllegalArgumentException immediately when duplicate keys are
* provided.
* Add a key-value pair into the built map. If duplicate keys are provided, the first value will be kept and the second
* value will be ignored, and the SDK will log an error.
*
* @return Returns a reference to this object so that method calls can
* be chained together.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,18 +71,13 @@ public void testOfBuilder() {
}

@Test
public void testErrorOnDuplicateKeys() {
try {
Map<Integer, String> builtMap = new ImmutableMap.Builder<Integer, String>()
.put(1, "one")
.put(1, "two")
.build();
fail("IllegalArgumentException expected.");
} catch (IllegalArgumentException iae) {
// Ignored or expected.
} catch (Exception e) {
fail("IllegalArgumentException expected.");
}
public void putDuplicateKeys_keepsFirstOneAndDoesNotThrowError() {
Map<Integer, String> builtMap = new ImmutableMap.Builder<Integer, String>()
.put(1, "one")
.put(1, "two")
.build();

assertEquals("one", builtMap.get(1));
}

@Test
Expand Down
Loading