简体   繁体   中英

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.

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();

 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> .

So how to resolve this issue **if I need Set, to Return an empty Collection and not null or nor conversion to List<Object> ?

Use Collections.emptySet() instead of Collections.emptyList() .

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

For more information, read the javadocs .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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