Mic*_*ael 2 java generics static-methods
我有这种静态方法
public static List<? extends A> myMethod(List<? extends A> a) {
// …
}
Run Code Online (Sandbox Code Playgroud)
我正在使用它
List<A> oldAList;
List<A> newAList = (List<A>) MyClass.myMethod(oldAList);
Run Code Online (Sandbox Code Playgroud)
由于未经检查的强制转换,这会发出警告List<A>.有没有办法避免演员?
你需要定义返回的类型匹配参数(并扩展A)
public static <T extends A> List<T> myMethod(List<T> a) {
// …
}
Run Code Online (Sandbox Code Playgroud)
然后你就可以写了
List<E> list1 = .... some list ....
List<E> list2 = myMethod(list1); // assuming you have an import static or it's in the same class.
Run Code Online (Sandbox Code Playgroud)
要么
List<E> list2 = SomeClass.myMethod(list1);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
631 次 |
| 最近记录: |