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?
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:
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With