Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type Safety warning when trying to avoid returning NULL

In Eclipe, Java, I'm working on a method that does a bunch of stuff and at the end needs to return a generated list with argument Element. It is possible that this list is null in which case I want the method to return an empty list. This is to prevent needing if(list != null) checks everywhere since for statements work with empty lists.

I do this in the following way:

return tempList == null ? Collections.EMPTY_LIST : tempList;

This however gives the following warning :

Type Safety: The expression of type List needs unchecked conversion to comfirm to List<Element>.

All the solutions Eclipse suggest don't work. I'm guessing the problem is with Collections.EMPTY_LIST returning a generic list, but have no idea how to solve this.

like image 839
Sven Avatar asked Dec 10 '22 00:12

Sven


1 Answers

Use this syntax if you really want to avoid local variable declaration.

return elements == null ? Collections.<Element>emptyList() : elements;
like image 186
Rangi Lin Avatar answered Jan 08 '23 23:01

Rangi Lin