Consider code:
public List<Products> listProducts(){
...
return (List<Products>) query.list(); // returning a list containing Products objects
}
Use of generics in method return types is always preferred as:
public List<Products> listProducts(){
...
}
1)But is it preferable to use generics in return statements?
as:
return (List<Products>) query.list();
2)Is there any harm in using simple List in return statement as:
return (List) query.list();
There won’t be any problems, bar some compiler warnings about raw types. Some fun stuff can happen if your underlying types are not consistent. Assume this situation:
Results in a runtime exception:
Now if instead you used:
The compiler would have complained:
Conclusion: Using generics is always a good idea because it can save you some runtime headaches.