Java Generics,如何在使用类层次结构时避免未经检查的赋值警告?
我想使用一个使用generics参数的方法,并在类层次结构上返回generics结果。
编辑: 没有 SupressWarnings(“未选中”)答案允许:-)
这是一个说明我的问题的示例代码:
import java.util.*; public class GenericQuestion { interface Function {R apply(F data);} static class Fruit {int id; String name; Fruit(int id, String name) { this.id = id; this.name = name;} } static class Apple extends Fruit { Apple(int id, String type) { super(id, type); } } static class Pear extends Fruit { Pear(int id, String type) { super(id, type); } } public static void main(String[] args) { List apples = Arrays.asList( new Apple(1,"Green"), new Apple(2,"Red") ); List pears = Arrays.asList( new Pear(1,"Green"), new Pear(2,"Red") ); Function fruitID = new Function() { public Integer apply(Fruit data) {return data.id;} }; Map appleMap = mapValues(apples, fruitID); Map pearMap = mapValues(pears, fruitID); } public static Map mapValues( List values, Function function) { Map map = new HashMap(); for (V v : values) { map.put(function.apply(v), v); } return map; } }
如何从这些调用中删除一般exception:
Map appleMap = mapValues(apples, fruitID); Map pearMap = mapValues(pears, fruitID);
额外的问题:如果我以这种方式声明fruitId函数,如何删除编译错误:
Function fruitID = new Function() {public Integer apply(Fruit data) {return data.id;}};
在处理层次结构时,我对generics非常困惑。 任何关于使用的良好资源的指针都将非常感激。
2个小变化:
public static void main(final String[] args){ // ... snip // change nr 1: use a generic declaration final Function fruitID = new Function(){ @Override public Integer apply(final Fruit data){ return data.id; } }; // ... snip } public static Map mapValues(final List values, // change nr. 2: use super V> instead of final Function super V, K> function){ // ... snip }
供参考,请阅读:
获取原则