senzacionale
senzacionale

Reputation: 20936

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. Only options for offer are AbstractOfferDto or OfferDto.

How can I use generics for this example?

Upvotes: 2

Views: 112

Answers (2)

NPE
NPE

Reputation: 500913

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:

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

Upvotes: 4

wrm
wrm

Reputation: 1908

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

Upvotes: 6

Related Questions