简体   繁体   English

应返回空数组和集合而不是 null (java:S1168)

[英]Empty arrays and collections should be returned instead of null (java:S1168)

As I installed SonarLint plugin in my eclipse IDE, i got the above (Heading) Major Issue.当我在 Eclipse IDE 中安装 SonarLint 插件时,我遇到了上述(标题)主要问题。

Let's Assume:让我们假设:

public List<CountryModel> getAllCountries() { 
    return null;        //***SonarLint Suggesest*: return an empty Collection instead of null.**
}

Can be modified (fixed) as below:可以修改(固定)如下:

public List<CountryModel> getAllCountries() {
    return Collections.emptyList();
}

Note: Similarly, I have a Set of CountryModel as below, and I tried to return Collections.emptyList();注意:同样,我有一个如下的 CountryModel 集,我尝试return Collections.emptyList();

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

I got Exception saying :我有例外说:

Type mismatch: cannot convert from
List<Object> to Set<CountryModel>.

Also Suggested saying, converting Set to List<Object> .还建议说,将Set转换为List<Object>

So how to resolve this issue **if I need Set, to Return an empty Collection and not null or nor conversion to List<Object> ?那么如何解决这个问题 **如果我需要设置,返回一个空的集合而不是 null 或者也不是转换为List<Object>

Use Collections.emptySet() instead of Collections.emptyList() .使用Collections.emptySet()而不是Collections.emptyList()

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

For more information, read the javadocs .有关更多信息,请阅读javadocs

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM