簡體   English   中英

Java通用方法調用

[英]Java generic method call

考慮以下代碼:

public class MainClass {
    public static void main(String[] args) {
        ArrayList<HashMap<String, Integer>> collection = new ArrayList<>();
        ArrayList<HashMap<String, Integer>> outCollecttion = <String, Integer, HashMap<String, Integer>, ArrayList<HashMap<String, Integer>>>doSomeWork(collection);
    }

    public static <V extends Object, U extends Object, K extends Map<V, U>, J extends Collection<K>> Collection<K> doSomeWork(J collection) {
        Collection<K> result = new ArrayList<>();

        for (K element : collection) {
            result.add(element); //here is supposed other code, this is just example
        }

        return result;
    }
}

我想對包含某些通用類型的映射的通用集合做一些工作。 我知道Java很難確定復雜的泛型表達式,因此我在方法調用之前放置了顯式類型:

<String, Integer, HashMap<String, Integer>, ArrayList<HashMap<Integer, String>>>doSomeWork(collection)

但是編譯器不會編譯它。 我確實知道這可能與以下事實有關:我試圖在泛型類型中使用泛型類型,但是我不知道如何在不使用強制類型轉換的情況下編寫此方法,而不是不贊成使用警告(我通常使用- Xlint:未選中的標志)。

首先,當您想顯式提供類型參數時,必須從其類中調用該方法:

... = MainClass.<String, Integer, HashMap<String, Integer>, ArrayList<HashMap<String, Integer>>>doSomeWork(collection);

其次,您的方法返回Collection<K> ,但是將變量聲明為ArrayList<...> 以下對我有用:

Collection<HashMap<String, Integer>> outCollecttion = ...

您無需在分配中使用泛型。

Collection<HashMap<String, Integer>> outCollecttion = doSomeWork(collection);

暫無
暫無

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

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