要避免在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循環中遇到空指針異常。