Skip to content

Commit 4350fc2

Browse files
committed
List constructor arg initialized correctly
DataBinder now uses the calculated List size rather than the number of indexes to initialize the list. Closes gh-34145
1 parent 59ed468 commit 4350fc2

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

spring-context/src/main/java/org/springframework/validation/DataBinder.java

+3-1
Original file line numberDiff line numberDiff line change
@@ -1060,7 +1060,9 @@ private <V> List<V> createList(
10601060
}
10611061
int size = (indexes.last() < this.autoGrowCollectionLimit ? indexes.last() + 1 : 0);
10621062
List<V> list = (List<V>) CollectionFactory.createCollection(paramType, size);
1063-
indexes.forEach(i -> list.add(null));
1063+
for (int i = 0; i < size; i++) {
1064+
list.add(null);
1065+
}
10641066
for (int index : indexes) {
10651067
list.set(index, (V) createObject(elementType, paramPath + "[" + index + "].", valueResolver));
10661068
}

spring-context/src/test/java/org/springframework/validation/DataBinderConstructTests.java

+18
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,24 @@ void listBinding() {
121121
assertThat(list.get(2).param1()).isEqualTo("value3");
122122
}
123123

124+
@Test // gh-34145
125+
void listBindingWithNonconsecutiveIndices() {
126+
MapValueResolver valueResolver = new MapValueResolver(Map.of(
127+
"dataClassList[0].param1", "value1", "dataClassList[0].param2", "true",
128+
"dataClassList[1].param1", "value2", "dataClassList[1].param2", "true",
129+
"dataClassList[3].param1", "value3", "dataClassList[3].param2", "true"));
130+
131+
DataBinder binder = initDataBinder(ListDataClass.class);
132+
binder.construct(valueResolver);
133+
134+
ListDataClass dataClass = getTarget(binder);
135+
List<DataClass> list = dataClass.dataClassList();
136+
137+
assertThat(list.get(0).param1()).isEqualTo("value1");
138+
assertThat(list.get(1).param1()).isEqualTo("value2");
139+
assertThat(list.get(3).param1()).isEqualTo("value3");
140+
}
141+
124142
@Test
125143
void mapBinding() {
126144
MapValueResolver valueResolver = new MapValueResolver(Map.of(

0 commit comments

Comments
 (0)