簡體   English   中英

Java Generics,如何在使用類層次結構時避免未經檢查的賦值警告?

[英]Java Generics, how to avoid unchecked assignment warning when using class hierarchy?

我想使用一個使用泛型參數的方法,並在類層次結構上返回泛型結果。

編輯: 沒有 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;}};

在處理層次結構時,我對泛型非常困惑。 任何關於使用的良好資源的指針都將非常感激。

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
}

供參考,請閱讀:

獲取原則

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM