-1

I have the following code:

private Set<? extends DecisionGroupDto> parentGroups = new HashSet<>();

public DecisionDto(Decision decision) {
    super(decision);
    if (decision != null) {
        Set<? extends DecisionGroup> parentGroups = decision.getParentGroups();
        if (CollectionUtils.isNotEmpty(parentGroups)) {
            for (DecisionGroup parentGroup : parentGroups) {
                this.parentGroups.add(new DecisionGroupDto(parentGroup));
            }
        }
    }
}

right now the following line:

this.parentGroups.add(new DecisionGroupDto(parentGroup));

fails with the following error:

Required type: capture of ? extends DecisionGroupDto
Provided:DecisionGroupDto

How to allow this.parentGroups accept not only derived classes from DecisionGroupDto but also and DecisionGroupDto itself?

alexanoid
  • 24,051
  • 54
  • 210
  • 410

1 Answers1

0

You have to use super instead of extends

private Set<? extends DecisionGroupDto> parentGroups = new HashSet<>();

public DecisionDto(Decision decision) {
    super(decision);
    if (decision != null) {
        Set<? super DecisionGroup> parentGroups = decision.getParentGroups();
        if (CollectionUtils.isNotEmpty(parentGroups)) {
            for (DecisionGroup parentGroup : parentGroups) {
                this.parentGroups.add(new DecisionGroupDto(parentGroup));
            }
        }
    }
}

To specify the lower bounding class of a type wildcard, the super keyword is used. This keyword indicates that the type argument is a supertype of the bounding class. Adding to such a list requires either elements of type DecisionGroup, any subtype of DecisionGroup or null (which is a member of every type).