簡體   English   中英

如何構建 class 和構造函數泛型以使用泛型方法?

[英]How to build a class and constructor generic to use generic methods?

我無法理解如何構建 class 和構造函數泛型。 我對 generics 還很陌生,但現在我有了基本的了解。

以下方法有效:

@Override
public <T> List<T> groupProceeds(Collection<? extends T> e, Function<? super T, Integer> p) {
    int from = 10001;
    int to = 10070;
    int sum = 1010000;

    return buildGroup(e, p, from, to, sum);
}

如何在 class 中使用此方法? class 應該具有構造函數和通用屬性。

這是我的方法之一,這是行不通的。 但我也不知道如何解決。

public class StandardStructure<T, P> {

    private T entities;
    private P property;


    public StandardStructure (Collection<? extends T> entities, Function<? super T, Integer> property) {
        this.entities = entities;
        this.property = property;

    }

    @Override
    public <T> List<T> groupProceeds(Collection<? extends T> e, Function<? super T, Integer> p) {
        int from = 10001;
        int to = 10070;
        int sum = 1010000;

        return buildGroup(e, p, from, to, sum);
    }
}

構造 class 時,應將集合實體Function 屬性傳遞給方法。

我需要幫助設置 class 和構造函數泛型。

我會想到幾點:

  • 您不需要 generics 中的P類型,因為您的property屬性的類型以T表示

  • 如果您將entitiesproperty作為 class 變量,則無需將它們傳遞給您的groupProceeds方法

  • 你不能在這里使用@Override ,因為你沒有擴展任何 class 或實現任何接口

  • 您不應將該方法設為泛型,因為它會隱藏 class 泛型。 您需要與 class T 相同的 T。

試試這種方式:

public class StandardStructure<T> {

    private Collection<? extends T> entities;
    private Function<? super T, Integer> property;

    public StandardStructure (Collection<? extends T> entities, Function<? super T, Integer> property) {
        this.entities = entities;
        this.property = property;
   }

    public List<T> groupProceeds() {
        int from = 10001;
        int to = 10070;
        int sum = 1010000;

        return buildGroup(entities, property, from, to, sum);
    }

    private List<T> buildGroup(Collection<? extends T> e,  Function<? super T, Integer> p, int from, int to, int sum) {
        /* Whatever that does */
    }
}

或者,如果您想將參數傳遞給方法,則不需要它們作為 class 上的屬性,甚至不再需要構造函數:

public class StandardStructure<T> {

    public List<T> groupProceeds(Collection<? extends T> entities, Function<? super T, Integer> property) {
        int from = 10001;
        int to = 10070;
        int sum = 1010000;

        return buildGroup(entities, property, from, to, sum);
    }

    private List<T> buildGroup(Collection<? extends T> e,  Function<? super T, Integer> p, int from, int to, int sum) {
         /* Whatever that does */
    }
}

暫無
暫無

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

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