gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:14:39 24 4
gpt4 key购买 nike

假设我有一个接口(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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com