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

1.5k views Asked by At

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

1

There are 1 answers

0
Stephen C On

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

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

For more information, read the javadocs.