Applying Jörg Gottschling's patch from LANG-358 with Thomas Menzel's naming from LANG-550 and some of his tests. This adds a firstNonNull method to ObjectUtils.

git-svn-id: https://svn.apache.org/repos/asf/commons/proper/lang/trunk@833016 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Henri Yandell 2009-11-05 07:25:54 +00:00
parent 928950c9bf
commit acb16f7348
2 changed files with 47 additions and 0 deletions

View File

@ -318,4 +318,36 @@ public class ObjectUtils {
}
}
/**
* <p>Returns the first passed value which is not <code>null</code> or
* <code>null</code> otherwise.</p>
*
* <pre>
* ObjectUtils.firstNonNull(null, null) = null
* ObjectUtils.firstNonNull(null, "") = ""
* ObjectUtils.firstNonNull(null, null, "") = ""
* ObjectUtils.firstNonNull(null, "zz") = "zz"
* ObjectUtils.firstNonNull("abc", *) = "abc"
* ObjectUtils.firstNonNull(null, "xyz", *) = "xyz"
* ObjectUtils.firstNonNull(Boolean.TRUE, *) = Boolean.TRUE
* ObjectUtils.firstNonNull() = null
* </pre>
*
* @param values the values to test, may be <code>null</code> or empty
*
* @return The first value from <code>values</code> which is not
* <code>null</code> or <code>null</code> otherwise.
*/
public static <T> T firstNonNull(T... values) {
// This is a trivial implementation. There may be faster ones.
// According to the JRE Libraries, overloading the method with fixed
// parameter sizes may be faster.
for (T val : values) {
if (val != null && val != ObjectUtils.NULL) {
return val;
}
}
return null;
}
}

View File

@ -216,4 +216,19 @@ public class ObjectUtilsTest extends TestCase {
assertNull( ObjectUtils.min((String)null, (String)null) );
}
public void testFirstNonNull() {
assertEquals(null, ObjectUtils.firstNonNull(null, null));
assertEquals("", ObjectUtils.firstNonNull(null, ""));
assertEquals("123", ObjectUtils.firstNonNull(null, null, "123", "456"));
assertEquals("123", ObjectUtils.firstNonNull("123", null, "456", null));
assertEquals(null, ObjectUtils.firstNonNull());
assertSame(Boolean.TRUE, ObjectUtils.firstNonNull(Boolean.TRUE));
assertNull(ObjectUtils.firstNonNull());
assertNull(ObjectUtils.firstNonNull(null, null));
assertSame("123", ObjectUtils.firstNonNull(null, ObjectUtils.NULL, "123", "456"));
assertSame("456", ObjectUtils.firstNonNull(ObjectUtils.NULL, "456", "123", null));
assertNull(ObjectUtils.firstNonNull(null, null, ObjectUtils.NULL));
}
}