这是我写的:

public class LinkedListDeque<Whatever> {
    private class Node {
        private Whatever item;
        private Node prev;
        private Node next;

        private Node(Whatever i, Node p, Node n) {
            item = i;
            prev = p;
            next = n;
        }
    }

    private Node sentinel;
    private int size;

    /** Creates an empty Deque. */
    public LinkedListDeque() {
        sentinel = new Node(null, sentinel, sentinel);
        size = 0;
    }
}


现在,我想用类似于null的东西替换底部第四行中的Integer 1,然后我的IDE(Intellij)告诉我',' or ')' expected

这是问题:

我想在此构造函数中设置sentinel.item equals to 1,这可能吗?

退一步,是否有其他代码可以安全地替换代码null

最佳答案

我认为您的真正问题是实施不正确:


您的LinkedListDeque具有sentinel节点,即队列的头。因此,如果队列为空,则size = 0sentinel = null;
将新项目添加到队列时,您必须检查其是否为空(即size = 0sentinel = null)。如果为空,则只需创建新的Node,否则将新节点添加到队列的末尾;
根据以上内容,您不应更改Node.item,即应为finalprivate Whatever item


我认为您的课程可能看起来像这样(这只是示例):

public final class LinkedListDeque<Whatever> {

    private class Node {

        private final Whatever item;
        private Node prev;
        private Node next;

        private Node(Whatever item) {
            this.item = item;
        }
    }

    private Node sentinel;
    private int size;

    public void add(Whatever item) {
        Node node = new Node(item);

        if (size != 0) {
            node.next = sentinel;
            sentinel.prev = node;
        }

        sentinel = node;
        size++;
    }

}

关于java - 如何在通用类构造函数中为一个变体指定特定类型?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50868505/

10-10 11:17