我试着像那样绕圈

// ArrayList tourists

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

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


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

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


当前回答

这是从数组列表中删除默认空值的简单方法

     tourists.removeAll(Arrays.asList(null));  

从数组列表中删除字符串值“null”

       tourists.removeAll(Arrays.asList("null"));  

其他回答

这是从数组列表中删除默认空值的简单方法

     tourists.removeAll(Arrays.asList(null));  

从数组列表中删除字符串值“null”

       tourists.removeAll(Arrays.asList("null"));  

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

效率不高,但时间短

while(tourists.remove(null));

Objects类有一个非空谓词,可以与过滤器一起使用。

例如:

tourists.stream().filter(Objects::nonNull).collect(Collectors.toList());
list.removeAll(Collections.singleton(null));

如果你在数组上使用它,它会抛出UnsupportedException。asList因为它给了你不可变的副本,所以它不能被修改。请参阅下面的代码。它创建可变副本,不会抛出任何异常。

public static String[] clean(final String[] v) {
    List<String> list = new ArrayList<String>(Arrays.asList(v));
    list.removeAll(Collections.singleton(null));
    return list.toArray(new String[list.size()]);
}