我试着像那样绕圈

// ArrayList tourists

for (Tourist t : tourists) {
    if (t != null) {     
        t.setId(idForm); 
    }   
}

但这并不好。谁能给我一个更好的解决办法?


一些有用的基准可以帮助你做出更好的决定:

While循环,For循环和迭代器性能测试


当前回答

类似于@Lithium的答案,但不抛出“列表可能不包含类型null”错误:

   list.removeAll(Collections.<T>singleton(null));

其他回答

我摆弄了一下,发现trimToSize()似乎可以工作。我是在Android平台上工作,所以可能会有所不同。

我们可以使用迭代器for the same删除所有空值。

Iterator<Tourist> itr= tourists.iterator();
while(itr.hasNext()){
    if(itr.next() == null){
        itr.remove();
    }
}

Try:

tourists.removeAll(Collections.singleton(null));

阅读Java API。代码将为不可变列表抛出java.lang.UnsupportedOperationException(例如使用Arrays.asList创建的列表);更多细节请看这个答案。

我主要用这个:

list.removeAll(Collections.singleton(null));

但是在我学习了Java 8之后,我改用了这个:

List.removeIf(Objects::isNull);

如果你更喜欢不可变的数据对象,或者你不想破坏输入列表,你可以使用Guava的谓词。

ImmutableList.copyOf(Iterables.filter(tourists, Predicates.notNull()))