a Learner
a Learner

Reputation: 5042

use of generics in return statements

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

Upvotes: 4

Views: 134

Answers (1)

Tudor
Tudor

Reputation: 62439

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:

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

Results in a runtime exception:

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

Now if instead you used:

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

The compiler would have complained:

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

Conclusion: Using generics is always a good idea because it can save you some runtime headaches.

Upvotes: 6

Related Questions