简体   繁体   English

如何使用不同输入的相同方法使用泛型

[英]How to use generics for the same method with different input

private Set<String> extractOfferKeysForAbstractOffers(List<AbstractOfferDto> selectedOffers) {
        Set<String> offerKeys = new HashSet<String>();
        for (AbstractOfferDto offer : selectedOffers) {
            offerKeys.add(offer.getOfferKey());
        }
        return offerKeys;
    }

 private Set<String> extractOfferKeysForOffers(List<OfferDto> selectedOffers) {
        Set<String> offerKeys = new HashSet<String>();
        for (OfferDto offer : selectedOffers) {
            offerKeys.add(offer.getOfferKey());
        }
        return offerKeys;
    }

Instead of using almost the same method just input is different I want to use generics. 而不是使用几乎相同的方法只是输入是不同的我想使用泛型。 I create it like this. 我这样创造它。

private <T> Set<String> extractOfferKeysForOffers(List<T> offers) {
        Set<String> offerKeys = new HashSet<String>();
        for (T offer : offers) {
            offerKeys.add(offer.getOfferKey());
        }
        return offerKeys;
    }

but problem is that offer.getOfferKey() is not recognized. 但问题是不能识别offer.getOfferKey() Only options for offer are AbstractOfferDto or OfferDto . 提供的选项只有AbstractOfferDtoOfferDto

How can I use generics for this example? 如何在此示例中使用泛型?

Tell the compiler about the abstract type: 告诉编译器有关抽象类型的信息:

private <T extends AbstractOfferDto> Set<String> extractOfferKeysForOffers(List<T> offers) {
        Set<String> offerKeys = new HashSet<String>();
        for (T offer : offers) {
            offerKeys.add(offer.getOfferKey());
        }
        return offerKeys;
    }

Yes you can: 是的你可以:

  public interface IOffer {
     String getOfferKey();
  }

  public class OfferDto implements IOffer { ... }

  public class AbstractOfferDto implements IOffer { ... }

  class X {    
    private <T extends IOffer> Set<String> extractOfferKeysForOffers(List<T> offers) {
        Set<String> offerKeys = new HashSet<String>();
        for (T offer : offers) {
            offerKeys.add(offer.getOfferKey());
        }
        return offerKeys;
    }
  }

The above is a general solution. 以上是一般解决方案。 If OfferDto extends AbstractOfferDto , the extra interface is not needed: 如果OfferDto扩展AbstractOfferDto ,则不需要额外的接口:

  class X {    
    private <T extends AbstractOfferDto> Set<String> extractOfferKeysForOffers(List<T> offers) {
        Set<String> offerKeys = new HashSet<String>();
        for (T offer : offers) {
            offerKeys.add(offer.getOfferKey());
        }
        return offerKeys;
    }
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM