3 回答

TA貢獻1878條經(jīng)驗 獲得超4個贊
具有流使用率的另一個版本(需要Java 8或更高版本),并且檢查的版本catalogue不是null:
public Country findCountry(String countryName) {
if (catalogue == null) {
return null;
}
return Arrays.stream(catalogue)
.filter(country -> country.getName().equals(countryName))
.findAny()
.orElse(null);
}

TA貢獻1804條經(jīng)驗 獲得超3個贊
您可以將返回值初始化為null,并且僅在循環(huán)中找到它時才進行設(shè)置:
public Country findCountry(String countryname) {
// initialize a Country with null
Country foundCountry = null;
// try to find it
for (int i = 0; i < catalogue.length; i++) {
if (catalogue[i].getName().equals(countryname)) {
// set it if found
foundCountry = catalogue[i];
}
}
// if not found, this returns null
return foundCountry;
}
添加回答
舉報