可以通过如下代码实现对传入参数为null的情况进行处理:
public static Collection addAllSafe(Collection collection, T... elements) {
return (elements == null) ? Collections.emptyList() : CollectionUtils.addAll(collection, elements);
}
在这个方法中,我们首先检查传入的元素数组是否为null。如果是null,则返回一个空集合;否则,我们再调用Apache Commons CollectionUtils中的addAll方法将元素添加到集合中。
使用该方法的示例代码如下:
List list = new ArrayList();
addAllSafe(list, "a", "b", "c");
addAllSafe(list, null); // No exception thrown; list is unchanged
addAllSafe(list, "d", null, "e"); // NullPointerException thrown
参考链接:https://stackoverflow.com/questions/13936000/unexpected-behaviour-of-apache-commons-collectionutils-addallcollection-co