【问题标题】:How can I have both of these constructors?我怎样才能拥有这两个构造函数?
【发布时间】:2021-03-24 22:46:33
【问题描述】:

我正在为源自尼泊尔的名为 Tigers and Goats(或 Tigers and Sheep)的游戏制作基于树的 AI。我现在开始为树创建类,但我遇到了一个错误,我的构造函数是相同的,尽管它们使用不同类型的列表。

这是我的两个构造函数:

public MoveTree(List<MoveTree> children, MoveTree parent)
{
    this.children = children;
    this.parent = parent;
}
public MoveTree(List<Move> moves, MoveTree parent)
{
    this.moves = moves;
    this.parent = parent;
}

我正在使用 intellij,它给了我此处显示的错误

如何在仍然拥有两个构造函数的同时避免此错误?我希望能够在不过多更改构造函数的情况下做到这一点,以便我可以有不同的方式来实现这个类以用于不同的目的

【问题讨论】:

标签: java intellij-idea arraylist constructor type-erasure


【解决方案1】:

你不能两者兼得。使用 builder 模式(正式样式 - 此处未显示)或工厂方法(更简单 - 显示):

private MoveTree(MoveTree parent) {
    this.parent = parent;
}

public static MoveTree createWithMoveTree(List<MoveTree> children, MoveTree parent) {
    MoveTree moveTree = new MoveTree(parent);
    moveTree.children = children;
    return moveTree;
}

public static MoveTree createWithMoves(List<Move> moves, MoveTree parent) {
    MoveTree moveTree = new MoveTree(parent);
    moveTree.moves = moves;
    return moveTree;
}

【讨论】:

    猜你喜欢
    • 2014-03-31
    • 1970-01-01
    • 1970-01-01
    • 2019-09-04
    • 2021-10-24
    • 2011-04-27
    • 2011-07-20
    • 1970-01-01
    • 2018-03-25
    相关资源
    最近更新 更多