初始化和声明对象和方法

时间:2016-06-12 00:43:02

标签: java object constructor

我有以下问题,我不知道如何解决它。我正在寻找建议。我有一个实例数据(见下文)。这就是我想要做的事情:

在声明或构造函数中,应将killring初始化为new KillList()

private KillList killring;

KillList是另一个类的子类。整个程序处理列表:LinkedLists和ArrayList。 构造函数将ArrayList中的元素添加到Killring中。每次添加一个新节点到链接列表的末尾。

这是我到目前为止所做的:

public class AssassinManager {

private static class AssassinNode {
    private String player; 
    private String killer; 
    private AssassinNode next;
    private AssassinNode(String name) { // to be altered 
        this.player = name; 
        this.killer = null; 
        this.next = null;
    } 
}// End of AssassinNode - DONE

private KillList killring; //KillList object
private AssassinNode graveyard; //AssassinNodeData object 

/* Constructor add names from arralyist to killring 
without altering elements in arraylist */
public AssassinManager (ArrayList<String> players) {
    if (players == null || players.isEmpty() == true) {
        throw new IllegalArgumentException();
    }
    killring = new AssassinNode(players.get(0)); // AN ERROR IS PRESENTED HERE
}

这就是我目前为KillList所做的:

public class KillList extends AssassinNodeData {

public KillList(String player) {
    super(player);
}

可能的答案:

public AssassinManager (ArrayList<String> players) {
    if (players == null || players.isEmpty() == true) {
        throw new IllegalArgumentException();
    }
    killring = new KillList(players.get(0));
    KillList node = killring; 
    for (int i = 1; i < players.size(); i++) {
        node.next = new KillList(players.get(i));
        node = node.next; 
    }
}

1 个答案:

答案 0 :(得分:0)

它不能编译的原因是你正在调用AssasinNode的构造函数来创建KillList,你需要使用KillList的构造函数,所以killring = new KillList(players.get(0))

但是我想指出一个逻辑上的错误:你正在创建一个&#34; KillList&#34;但它不能包含更多的那个玩家。如果您想要一个正确的列表,您需要添加一个列表成员字段以及在KillList内添加和删除该列表的正确方法。