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
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) {
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.

Post a Comment Default Comments

  1. This method may hold good for Collections too. How about a method with this signature

    public status Collection notNull(final Collection)

  2. Whats that "SuppressWarning" annotation in your code?

  3. Thats just for the compiler to stop complaining about certain warnings...

  4. "Suppress Warning",
    reason: In the above snipset, ArrayList has been used as a raw type,it can be rewritten by specifiying Object as a reference type. Its java's ususal warning.
    Anyway smartly written :)
    Food for thought>> Do i always have to typecast the the array ?

  5. Thanks Shubhashish! The @SuppressWarning annotation is to suppress the unwanted warning which will be displayed by Compiler. If you compile this file without @SuppressWarning annotation then it will give you this warning message.

    "Note: uses unchecked or unsafe operations.
    Note: Recompile with -Xlint:unchecked for details."

    If you want the compiler to ignore these errors then use @SuppressWarnings annotation. The "unchecked" option is "to suppress warnings relative to unchecked operations." There are many other options available for this annotation

    The eclipse documentation talks about it in more details.


Individuals who comment on FromDev at regular basis, will be rewarded in Top Commenter section. (Comments are selectively moderated so please do not spam)