SyntaxHighlighter JS

2013-01-20

Null safe for-each loop

If a collection is null when used in a for-each loop, it will result in a NullPointerException.  To prevent this, use the following utility method to return an empty list if the collection is null.


    public static <T> Collection<T> nullSafe(Collection<T> c) {
        return (c == null) ? Collections.<T>emptyList() : c;
    }

To use,

    Set<String> c = null;
    for(String s : nullSafe(c)) {
        System.out.println(s);
    }

No comments:

Post a Comment