簡體   English   中英

為實現接口的類實現通用方法

[英]Implementing a generic method for classes that implements an interface

最近,我決定深入研究Java,並在個人項目中使用Java。最后,我編寫了一個類以選擇加權值列表之間的隨機值。

我要做的第一件事是編寫一個接口IWeighable,它只有一個方法:

double getWeight();

因此,我想使用該隨機化器選擇的每個類都必須實現這樣的接口,以便能夠獲得選項的權重值。

現在,這是我直到最近才寫的內容(現在嘗試進行改進):

public IWeighable getRandomWeighable(List<IWeighable> weighables)
{
    double totalWeight = 0.0;

    for (IWeighable weighable : weighables)
    {
        if (weighable.getWeight() > 0)
            totalWeight += weighable.getWeight();
    }

    double selected = SRandom.randDouble() * totalWeight;

    for (IWeighable weighable : weighables)
    {
        double weight = weighable.getWeight();
        selected -= weight;

        if (selected <= 0)
            return weighable;
    }

    return null;
}

但是我剛剛意識到,這可能不是編碼的最佳方法。 為什么? 因為例如,如果我編寫一個實現“ IWeighable”的類“ Encounter”,則不能簡單地調用:

List<Encounter> encounters;
...
Encounter rEncounter = WeightedRandomizer.getInstance().getRandomWeighable(encounters);

因為“ encounters”的類型不是List <IWeighable>

我嘗試將“ getRandomWeighable”的簽名更改為:

public IWeighable getRandomWeighable(List<Class<? extends IWeighable>> weighables) {

但這需要大量的泛型工作,我很滿意,但是它們會引發各種異常,這是我希望在特定代碼中避免的事情。 我覺得有一種更輕松,更好的方式來編寫此代碼,我正努力尋找它。

有小費嗎?

親切的問候,並感謝您的幫助

編輯

抱歉,我只是想了一下,然后嘗試將getRandomWeighable簽名更改為:

public <T extends IWeighable> T getRandomWeighable(List<T> weighables)

我正在考慮刪除此問題,但可能對像我這樣的另一個Java新手很有用,所以不確定。

如果您的目標是接受具有IWeighable泛型類型的任何列表,則可以使用上界通配符 List<? extends IWeighable> List<? extends IWeighable>

public IWeighable getRandomWeighable(List<? extends IWeighable> weighables) {
  ...
}

暫無
暫無

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

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