简体   繁体   English

在返回语句中使用泛型

[英]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 ? 1)但是在返回语句中使用泛型是否更可取

as: 如:

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

2)Is there any harm in using simple List in return statement as: 2)在return语句中使用简单的List是否有任何危害:

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: 假设这种情况:

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) 线程“主”中的异常java.lang.ClassCastException:无法在test.Test.main(Test.java:13)上将java.lang.String强制转换为java.lang.Integer。

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. 结论 :使用泛型始终是一个好主意,因为它可以节省一些运行时的麻烦。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM