Java Array Utility methods - Trim/notNull for Array of Objects

This is another simple but useful Java Array Utility/Util method, which can be used to trim/remove all null Object values in an array. Doing this would eliminate a null check on every array element. This method returns null value if the input array itself is null. We can call this as trim of array, as it will return all not null objects in the result(trimming the size of array).
/**
* This Array utility or util method can be used to trim all
* the null values in the array.
* For input {"1", "2", null, "3","4"}
* the output will be {"1", "2", "3","4"}
*
* @param values
* @return Array of Object
*/
@SuppressWarnings("unchecked")
public static Object[] notNull(final Object[] values) {
if (values == null) {
return null;
}
ArrayList newObjectList = new ArrayList();
for (int i = 0, length = values.length; i < length; i++) {
if (values[i] != null) {
newObjectList.add(values[i]);
}
}
return newObjectList.toArray();
}

A notNull method for simple object is already a popular utility method, which is used by most programmers now. Checking Array with the same notNull can also be good idea. I am not sure how much performance boost we can get by doing this but I am open to thoughts on it. Please share your comment with us.

Related

Example Code 6755579636819129573

Post a Comment Default Comments

...

item