Java 集合 : Pass collection of children as collection of parents

标签 java generics collections

假设我有一个接口(interface)和一些类:

public interface IPanel<ComponentType extends Component> {
   public void addComponents(Set<ComponentType> components);
   public ComponentType create();
}

public class Button extends Component { }

public class LocalizedButton extends Button { }

public class ButtonsPanel implements IPanel<Button> {
    public void addComponents(Set<Button> components) { ... /* uses create() */ ; }
    public Button create() { return new Button(); }
}

public class LocalizedButtonsPanel extends ButtonsPanel {
    public Button create() { return new LocalizedButton(); }
}

然后我有一组 LocalizedButtons,当我调用时

final LocalizedButtonsPanel localizedButtonsPanel = new LocalizedButtonsPanel();
final Set<LocalizedButton> localizedButtonsSet = new LinkedHashSet<LocalizedButton>();
localizedButtonsPanel.addComponents(localizedButtonsSet);

我知道这个方法不适用于这个参数。 如果我尝试将此方法重载为 addComponents(Set<LocalizedButton> buttons)LocalizedButtonsPanel ,我当然会进行类型删除。

可能遗漏了某些模式,或者存在处理此架构以实现正确添加 LocalizedButton 集的技巧?


我得到了答案,我想让我的例子更具体——我的实现中有一些 validator ,所以我需要集合类型也存储为通用的,这是我使用的简化代码回答:

public interface IPanel<ComponentType extends Component, CollectionType extends Collection<? extends Component>> extends Validated<CollectionType> {
   public void addComponents(CollectionType components);
   public ComponentType create();
}

public class Button extends Component { }

public class LocalizedButton extends Button { }

public class ButtonsPanel implements IPanel<Button, Set<? extends Button>> {
    public void addComponents(Set<? extends Button> components) { ... /* uses create() */ ; }
    public Button create() { return new Button(); }
}

public class LocalizedButtonsPanel extends ButtonsPanel {
    public Button create() { return new LocalizedButton(); }
}

在这种情况下,它有效

最佳答案

将 addComponents() 签名更改为

public void addComponents(Set<? extends Button> components)

以便这些方法接受 Button 的子类集。 这样,您可以传递 Set<LocalizedButton>作为论据,因为 LocalizedButton延伸Button因此匹配 Set<? extends Button> 的参数类型.

关于Java 集合 : Pass collection of children as collection of parents,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3396182/

相关文章:

java - 什么时候绝对需要泛型数组——一个案例

java - 实现这样的迭代器?

java - 一组重名的集合?

Java RMI : Determining Caller process from Callee

generics - 奇怪的 JDK 行为,它应该编译吗?

c# - 构建通用过滤器参数输入接口(interface)?

java - 从没有位置的类 X 的 ArrayList 中获取类 X 的实例

java - 生成构造函数

java - 方法覆盖

java - 如何在资源中定义组合字符串?