2
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;
    }

我想使用泛型,而不是使用几乎相同的方法,只是输入不同。我像这样创建它。

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

但问题是offer.getOfferKey()不被认可。提供的唯一选项是AbstractOfferDtoOfferDto

我如何在这个例子中使用泛型?

4

2 回答 2

6

告诉编译器抽象类型:

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;
    }
于 2013-01-03T09:12:15.773 回答
4

是的你可以:

  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;
    }
  }

以上是通用解决方案。如果OfferDtoextends 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;
    }
  }
于 2013-01-03T09:12:57.357 回答