【问题标题】:Java method generic [duplicate]Java方法泛型[重复]
【发布时间】:2021-06-21 11:16:03
【问题描述】:

我有以下代码:

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

现在是以下行:

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

失败并出现以下错误:

Required type: capture of ? extends DecisionGroupDto
Provided:DecisionGroupDto

如何让this.parentGroups 不仅接受来自DecisionGroupDto 的派生类,还接受来自DecisionGroupDto 本身的派生类?

【问题讨论】:

  • 您必须将其声明为Set&lt;DecisionGroupDto&gt;。但这限制了您可以分配给 parentGroups 的内容(也许您不需要)
  • 你为什么首先使用? extends

标签: java generics java-11


【解决方案1】:

你必须使用 super 而不是 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));
            }
        }
    }
}

要指定类型通配符的下界类,使用 super 关键字。此关键字指示类型参数是边界类的超类型。添加到此类列表需要 DecisionGroup 类型的元素、DecisionGroup 的任何子类型或 null(它是每种类型的成员)。

【讨论】:

    猜你喜欢
    • 2015-05-16
    • 1970-01-01
    • 2022-08-14
    • 2015-10-08
    • 1970-01-01
    • 2016-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多