2011-03-15 12 views
8

Quiero usar un método que use parámetros genéricos y devuelva resultados genéricos en una jerarquía de clases.Java Generics, cómo evitar la advertencia de asignación sin marcar cuando se utiliza la jerarquía de clases?

de edición: noSupressWarnings ("sin control") respuesta permitida :-)

Aquí hay un código de ejemplo que ilustra mi problema:

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

Cómo eliminar la excepción genérica de éstos llamadas:

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

Pregunta adicional: cómo eliminar el error de compilación si declaro la función fruitId de esta manera:

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

Estoy muy confundido acerca de los genéricos cuando se trata de la jerarquía. Cualquier indicador de un buen recurso sobre el uso de y será muy apreciado.

Respuesta

10

2 pequeños cambios:

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 
} 

Como referencia, lea esto:

The get-put principle

+0

perfecto, muchas gracias. – Guillaume

Cuestiones relacionadas