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()
无法识别。只有优惠选项为AbstractOfferDto
或OfferDto
。
如何在此示例中使用泛型?
答案 0 :(得分: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;
}
答案 1 :(得分: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;
}
}
以上是一般解决方案。如果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;
}
}