要避免在Java的foreach循环中出现空指针异常(NullPointerException),你可以在访问集合元素之前检查它们是否为null。这里有一些建议:
Collections.emptyList()
。List<String> list = getList(); // getList() may return null
list = (list != null) ? list : Collections.emptyList();
for (String item : list) {
// do something with item
}
List<String> list = getList();
for (String item : list) {
if (item != null) {
System.out.println(item.toUpperCase());
} else {
// handle null value, e.g., log it or skip it
}
}
List<String> list = getList();
list.stream()
.filter(Objects::nonNull) // filter out null elements
.map(String::toUpperCase)
.forEach(System.out::println);
List<List<String>> nestedList = getNestedList();
if (nestedList != null) {
for (List<String> innerList : nestedList) {
if (innerList != null) {
for (String item : innerList) {
if (item != null) {
System.out.println(item.toUpperCase());
} else {
// handle null value
}
}
} else {
// handle null innerList
}
}
} else {
// handle null nestedList
}
通过遵循这些建议,你可以避免在Java的foreach循环中遇到空指针异常。