[英]Empty arrays and collections should be returned instead of null (java:S1168)
当我在 Eclipse IDE 中安装 SonarLint 插件时,我遇到了上述(标题)主要问题。
让我们假设:
public List<CountryModel> getAllCountries() {
return null; //***SonarLint Suggesest*: return an empty Collection instead of null.**
}
可以修改(固定)如下:
public List<CountryModel> getAllCountries() {
return Collections.emptyList();
}
注意:同样,我有一个如下的 CountryModel 集,我尝试return Collections.emptyList();
public Set<CountryModel> getAllCountries() {
return Collections.emptyList();
}
我有例外说:
Type mismatch: cannot convert from
List<Object> to Set<CountryModel>.
还建议说,将Set
转换为List<Object>
。
那么如何解决这个问题 **如果我需要设置,返回一个空的集合而不是 null 或者也不是转换为List<Object>
?
使用Collections.emptySet()
而不是Collections.emptyList()
。
public Set<CountryModel> getAllCountries() {
return Collections.emptySet();
}
有关更多信息,请阅读javadocs 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.