您最好验证从哪里获得该列表。
空列表就是您所需要的,因为空列表不会失败。
如果您从其他地方获得此列表,并且不知道是否可以,则可以创建一个实用程序方法并像这样使用它:
for( Object o : safe( list ) ) { // do whatever }当然
safe是:
public static List safe( List other ) { return other == null ? Collections.EMPTY_LIST : other;}
您最好验证从哪里获得该列表。
空列表就是您所需要的,因为空列表不会失败。
如果您从其他地方获得此列表,并且不知道是否可以,则可以创建一个实用程序方法并像这样使用它:
for( Object o : safe( list ) ) { // do whatever }当然
safe是:
public static List safe( List other ) { return other == null ? Collections.EMPTY_LIST : other;}