2017-06-01 89 views
0

我有一個接口Exec的實現通用接口

public interface Exec<T, U> { 
    U execute(final T context); 
} 

現在我可以有它實現接口Exec的如下

public class BatchExec<T, U> implements Exec<List<T>, List<U>> 

一類我的疑問是Exec的接受T和U爲類型參數和在這種情況下,我們將它作爲List和List傳遞,但BatchExec期望T和U?

+3

的'T'和''U'是完全無關的'T'和'U'在'Exec的'。將它們想象爲方法參數 - 多個方法可以具有相同名稱的參數。 –

回答

1

正如Oliver Charlesworth指出的那樣,在BatchExex<...>UT比在Exec<T, U>不同。即如果聲明BatchExec這樣的:

public class BatchExec<T, U> implements Exec<List<T>, List<U>> 

然後執行方法簽名將包含List<T>List<U>

public List<U> execute(List<T> context) 

這可能會造成混亂,以便讓我們創建與其他類型參數的OtherbatchExec

public class OtherBatchExec<P, Q> implements Exec<List<P>, List<Q>> { 
    @Override 
    public List<Q> execute(List<P> context) { 
     return null; 
    } 

} 

只是爲了證明它,你可以用同樣的方式調用它們的構造函數:

Exec<List<String>, List<Integer>> exec = new BatchExec<String, Integer>(); 
Exec<List<String>, List<Integer>> otherExec = new OtherBatchExec<String, Integer>(); 

爲了便於閱讀,我也將類型參數添加到構造函數調用中。您可以使用diamond operator太:在`BatchExec

Exec<List<String>, List<Integer>> exec = new BatchExec<>(); 
Exec<List<String>, List<Integer>> otherExec = new OtherBatchExec<>();