Using generics in return statements

Consider the code:

public List<Products> listProducts(){ ... return (List<Products>) query.list(); // returning a list containing Products objects } 

Using generics in a return type method is always preferable:

 public List<Products> listProducts(){ ... } 

1) But use preferred to use generics in return statements ?

as:

 return (List<Products>) query.list(); 

2) Is there any harm when using a simple list in a return statement like:

 return (List) query.list(); 
+4
source share
1 answer

There will be no problems, disable some compiler warnings about raw types. Some fun things can happen if your base types are incompatible. Let's pretend that:

 public static ArrayList<String> foo() { ArrayList<String> arrlist = new ArrayList<String>(); arrlist.add("asdf"); return arrlist; } public static List<Integer> bar() { return (List)foo(); } public static void main(String[] args) { List<Integer> list = bar(); System.out.println(list.get(0).doubleValue()); } 

Runtime exception results:

Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be passed to java.lang.Integer at test.Test.main (Test.java:13)

Now, if you used instead:

 public static List<Integer> bar() { return (List<Integer>)foo(); } 

The compiler would complain:

 Type mismatch: cannot convert from ArrayList<String> to List<Integer> 

Conclusion Using generics is always a good idea, as it can save you some headaches at runtime.

+6
source

Source: https://habr.com/ru/post/1432418/


All Articles