簡體   English   中英

通用接口的行為不符合預期

[英]Generic interface not behaving as expected

我有一個簡單的通用界面

public interface Person<T> {
    T foo(T other);
}

和一堂課

    public class Data<T extends Person> {

      public void doSomething(List<T> data){
         data.stream().reduce((a, b) -> (T)a.foo(b));
      }
  }

當我在將foo與功能foo一起使用時,假定該方法返回通用類型T ,編譯器表示無法返回它,因為它是錯誤的返回類型。

但是正如您所看到的,方法foo獲取並返回T

當我使用工作區myObj.foo(obj)自動完成時
我看到返回類型和參數類型是對象類型。 任何人都可以向我解釋為什么會這樣,為什么不是T型呢?

您必須指定Person的通用參數:

public class Data<T extends Person<T>> {
    ...
}

或將泛型稍微移動一下,我還看不到泛型參數的意義。

您的問題是您使用字母T代表兩個完全不同的類型參數Person通用類中的type參數和Data通用類中的type參數。

這些不是相同的參數-您已經通過對兩個字母使用相同的字母來使自己感到困惑。 但是,編譯器並不會混淆。 它完全正確地告訴您,您不能使用一個T代替另一個T

特別是,您嘗試將類型為foo返回的T的表達式foo轉換為另一種T

您在這里混淆了2個參數。 T

public interface Person<T> {
    T foo(T other);
}

在接口Person上定義一個參數。

public class Data<T extends Person> {
    public void doSomething(List<T> data) {
        data.stream().reduce((a, b) -> (T)a.foo(b));
    }
}

定義類型為Person Data類的參數,該參數隱式等於Person<Object>

因此List<T>是擴展Person的對象的列表,方法foo()具有Person第一個參數Object返回類型,而reduce期望返回類型為Person類型。

此代碼與您的代碼沒有什么不同:

public class Data<E extends Person> {
    public void doSomething(List<E> data) {
        data.stream().reduce((a, b) -> (E)a.foo(b));
    }
}

暫無
暫無

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

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