2011-03-15 55 views
8

我想使用一个使用泛型参数的方法,并在类层次结构上返回泛型结果。Java泛型,如何在使用类层次结构时避免未检查的赋值警告?

编辑:没有SupressWarnings( “未登记”)答案允许:-)

这里是一个示例代码,说明我的问题:

import java.util.*; 

public class GenericQuestion { 

    interface Function<F, R> {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<Apple> apples = Arrays.asList(
       new Apple(1,"Green"), new Apple(2,"Red") 
     ); 
     List<Pear> pears = Arrays.asList(
       new Pear(1,"Green"), new Pear(2,"Red") 
     ); 

     Function fruitID = new Function<Fruit, Integer>() { 
      public Integer apply(Fruit data) {return data.id;} 
     }; 

     Map<Integer, Apple> appleMap = mapValues(apples, fruitID); 
     Map<Integer, Pear> pearMap = mapValues(pears, fruitID); 
    } 

     public static <K,V> Map<K,V> mapValues(
       List<V> values, Function<V,K> function) { 

     Map<K,V> map = new HashMap<K,V>(); 
     for (V v : values) { 
      map.put(function.apply(v), v); 
     } 
     return map; 
    } 
} 

如何从这些删除的一般例外来电:

Map<Integer, Apple> appleMap = mapValues(apples, fruitID); 
Map<Integer, Pear> pearMap = mapValues(pears, fruitID); 

奖励问题:如何清除编译错误如果我以这种方式声明fruitId函数:

Function<Fruit, Integer> fruitID = new Function<Fruit, Integer>() {public Integer apply(Fruit data) {return data.id;}}; 

我在处理层次结构时非常困惑泛型。任何指向一个很好的资源的使用情况,将不胜感激。

回答

10

2个小的变化:

public static void main(final String[] args){ 

    // ... snip 

    // change nr 1: use a generic declaration 
    final Function<Fruit, Integer> fruitID = 
     new Function<Fruit, Integer>(){ 

      @Override 
      public Integer apply(final Fruit data){ 
       return data.id; 
      } 
     }; 

    // ... snip 
} 

public static <K, V> Map<K, V> mapValues(final List<V> values, 

    // change nr. 2: use <? super V> instead of <V> 
    final Function<? super V, K> function){ 

    // ... snip 
} 

仅供参考,请阅读本:

The get-put principle

+0

完美,非常感谢。 – Guillaume 2011-03-15 10:00:25

相关问题