首页 > 解决方案 > 我怎样才能拥有这两个构造函数?

问题描述

我正在为源自尼泊尔的名为 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,它给了我这里显示的错误 'MoveTree(List, MoveTree)' 与 'MoveTree(List, MoveTree)' 冲突; 两种方法都有相同的擦除

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

标签: javaintellij-ideaarraylistconstructortype-erasure

解决方案


你不能两者兼得。使用构建器模式(正式风格 - 此处未显示)或工厂方法(更容易 - 显示):

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

推荐阅读