Implements LANG-1050: Change nullToEmpty methods to generics. Thanks to James Sawle. This closes #33 in GitHub too.

git-svn-id: https://svn.apache.org/repos/asf/commons/proper/lang/trunk@1672244 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Duncan Jones 2015-04-09 06:27:15 +00:00
parent 2f67045b96
commit 7ef106b237
3 changed files with 55 additions and 0 deletions

View File

@ -22,6 +22,7 @@
<body>
<release version="3.5" date="tba" description="tba">
<action issue="LANG-1050" type="add" dev="djones" due-to="James Sawle">Change nullToEmpty methods to generics</action>
<action issue="LANG-1111" type="fix" dev="chas">Fix FindBugs warnings in DurationFormatUtils</action>
<action issue="LANG-1074" type="add" dev="djones" due-to="Haiyang Li">Add a method to ArrayUtils for removing all occurrences of a given element</action>
<action issue="LANG-1107" type="update" dev="chas">Fix parsing edge cases in FastDateParser</action>

View File

@ -458,6 +458,29 @@ public class ArrayUtils {
// nullToEmpty
//-----------------------------------------------------------------------
/**
* <p>Defensive programming technique to change a {@code null}
* reference to an empty one.</p>
*
* <p>This method returns an empty array for a {@code null} input array.</p>
*
* @param array the array to check for {@code null} or empty
* @param type the class representation of the desired array
* @return the same array, {@code public static} empty array if {@code null}
* @throws IllegalArgumentException if the type argument is null
*/
public static <T> T[] nullToEmpty(final T[] array, final Class<T[]> type) {
if(type == null) {
throw new IllegalArgumentException("The type must not be null");
}
if(array == null) {
return type.cast(Array.newInstance(type.getComponentType(), 0));
}
return array;
}
/**
* <p>Defensive programming technique to change a {@code null}
* reference to an empty one.</p>

View File

@ -356,6 +356,37 @@ public class ArrayUtilsTest {
//-----------------------------------------------------------------------
private class TestClass{}
@Test
public void testNullToEmptyGenericNull() {
TestClass[] output = ArrayUtils.nullToEmpty(null, TestClass[].class);
assertTrue(output != null);
assertTrue(output.length == 0);
}
@Test
public void testNullToEmptyGenericEmpty() {
TestClass[] input = new TestClass[]{};
TestClass[] output = ArrayUtils.nullToEmpty(input, TestClass[].class);
assertSame(input, output);
}
@Test
public void testNullToEmptyGeneric() {
TestClass[] input = new TestClass[]{new TestClass(), new TestClass()};
TestClass[] output = ArrayUtils.nullToEmpty(input, TestClass[].class);
assertSame(input, output);
}
@Test(expected=IllegalArgumentException.class)
public void testNullToEmptyGenericNullType() {
TestClass[] input = new TestClass[]{};
ArrayUtils.nullToEmpty(input, null);
}
@Test
public void testNullToEmptyBooleanNull() throws Exception {