【问题标题】:Empty arrays and collections should be returned instead of null (java:S1168)应返回空数组和集合而不是 null (java:S1168)
【发布时间】:2021-02-13 14:08:06
【问题描述】:

当我在我的 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&lt;Object&gt;

那么如何解决这个问题**如果我需要 Set,返回一个空集合而不是 null 或者也不转换为 List&lt;Object&gt;

【问题讨论】:

  • 你可以使用Collections.emptySet()

标签: java collections set sonarlint-eclipse


【解决方案1】:

使用Collections.emptySet() 而不是Collections.emptyList()

 public Set<CountryModel> getAllCountries() {
     return Collections.emptySet();
 }

欲了解更多信息,请阅读javadocs

【讨论】:

    猜你喜欢
    • 2020-05-15
    • 2019-05-14
    • 1970-01-01
    • 1970-01-01
    • 2013-07-22
    • 2020-07-15
    • 1970-01-01
    • 2011-05-21
    • 1970-01-01
    相关资源
    最近更新 更多