From 6db35fdb73fece9ccffa679b2e0e4f22cafa82fe Mon Sep 17 00:00:00 2001 From: Mihai Dumitrescu Date: Thu, 28 May 2020 15:31:20 +0200 Subject: [PATCH] Resolves gh-25140 --- .../springframework/util/CollectionUtils.java | 6 ++---- .../util/CollectionUtilsTests.java | 18 ++++++++++++++++++ 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/spring-core/src/main/java/org/springframework/util/CollectionUtils.java b/spring-core/src/main/java/org/springframework/util/CollectionUtils.java index 1cd16243fd31..2cabff4a225b 100644 --- a/spring-core/src/main/java/org/springframework/util/CollectionUtils.java +++ b/spring-core/src/main/java/org/springframework/util/CollectionUtils.java @@ -483,8 +483,7 @@ public MultiValueMapAdapter(Map> map) { @Override @Nullable public V getFirst(K key) { - List values = this.map.get(key); - return (values != null ? values.get(0) : null); + return firstElement(this.map.get(key)); } @Override @@ -521,7 +520,7 @@ public void setAll(Map values) { @Override public Map toSingleValueMap() { LinkedHashMap singleValueMap = new LinkedHashMap<>(this.map.size()); - this.map.forEach((key, value) -> singleValueMap.put(key, value.get(0))); + this.map.forEach((key, value) -> singleValueMap.put(key, firstElement(value))); return singleValueMap; } @@ -603,5 +602,4 @@ public String toString() { return this.map.toString(); } } - } diff --git a/spring-core/src/test/java/org/springframework/util/CollectionUtilsTests.java b/spring-core/src/test/java/org/springframework/util/CollectionUtilsTests.java index fa781881b0b5..e4dc13b8d7a3 100644 --- a/spring-core/src/test/java/org/springframework/util/CollectionUtilsTests.java +++ b/spring-core/src/test/java/org/springframework/util/CollectionUtilsTests.java @@ -17,6 +17,7 @@ package org.springframework.util; import java.util.ArrayList; +import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; @@ -28,6 +29,8 @@ import java.util.Properties; import java.util.Set; +import org.assertj.core.util.Maps; +import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; @@ -210,6 +213,21 @@ void hasUniqueObject() { assertThat(CollectionUtils.hasUniqueObject(list)).isFalse(); } + @Test + void noArrayIndexOutOfBoundsException() { + HashMap> mostlyEmptyMap = new HashMap<>(); + mostlyEmptyMap.put("test", new ArrayList<>()); + + + MultiValueMap multiValueMap = CollectionUtils.toMultiValueMap(mostlyEmptyMap); + Assertions.assertAll( + () -> assertThat(multiValueMap.getFirst(null)).isNull(), + () -> assertThat(multiValueMap.getFirst("test")).isNull(), + () -> assertThat(multiValueMap.toSingleValueMap().get(null)).isNull(), + () -> assertThat(multiValueMap.toSingleValueMap().get("test")).isNull() + ); + } + private static final class Instance {