Add position variant of ObjectUtils.addObjectToArray

Add an overloaded version of `ObjectUtils.addObjectToArray` that allows
inserts at a specific position.

Closes gh-28415
This commit is contained in:
Phillip Webb 2022-04-13 16:35:28 -07:00
parent 44bdcef0b9
commit f17372ebea
2 changed files with 25 additions and 4 deletions

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -250,6 +250,17 @@ public abstract class ObjectUtils {
* @return the new array (of the same component type; never {@code null})
*/
public static <A, O extends A> A[] addObjectToArray(@Nullable A[] array, @Nullable O obj) {
return addObjectToArray(array, obj, (array != null) ? array.length : 0);
}
/**
* Append the given object to the given array, returning a new array
* consisting of the input array contents plus the given object.
* @param array the array to append to (can be {@code null})
* @param obj the object to append
* @return the new array (of the same component type; never {@code null})
*/
public static <A, O extends A> A[] addObjectToArray(@Nullable A[] array, @Nullable O obj, int position) {
Class<?> compType = Object.class;
if (array != null) {
compType = array.getClass().getComponentType();
@ -261,9 +272,10 @@ public abstract class ObjectUtils {
@SuppressWarnings("unchecked")
A[] newArr = (A[]) Array.newInstance(compType, newArrLength);
if (array != null) {
System.arraycopy(array, 0, newArr, 0, array.length);
System.arraycopy(array, 0, newArr, 0, position);
System.arraycopy(array, position, newArr, position + 1, array.length - position);
}
newArr[newArr.length - 1] = obj;
newArr[position] = obj;
return newArr;
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -182,6 +182,15 @@ class ObjectUtilsTests {
assertThat(newArray[2]).isEqualTo(newElement);
}
@Test
void addObjectToArraysAtPosition() {
String[] array = new String[] {"foo", "bar", "baz"};
assertThat(ObjectUtils.addObjectToArray(array, "bat", 3)).containsExactly("foo", "bar", "baz", "bat");
assertThat(ObjectUtils.addObjectToArray(array, "bat", 2)).containsExactly("foo", "bar", "bat", "baz");
assertThat(ObjectUtils.addObjectToArray(array, "bat", 1)).containsExactly("foo", "bat", "bar", "baz");
assertThat(ObjectUtils.addObjectToArray(array, "bat", 0)).containsExactly("bat", "foo", "bar", "baz");
}
@Test
void addObjectToArrayWhenEmpty() {
String[] array = new String[0];