如何在泛型类构造函数中为一个变量赋予特定类型?

时间:2018-06-15 02:52:22

标签: java generics constructor

这就是我所写的:

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

1 个答案:

答案 0 :(得分:1)

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

  1. 您的sentinelsize = 0个节点,即队列的头部。因此,如果队列为空,则sentinel = nullsize = 0;
  2. 当您向队列添加新项目时,您必须检查它是否为空(即sentinel = nullNode)。如果它是空的,只需创建新的Node.item,否则将新节点添加到队列的末尾;
  3. 根据上述情况,您不应更改final,即它应为private Whatever itempublic 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++; } }
  4. 我认为你的课可能看起来像这个(这只是一个例子)

    <ScrollView
        ref={ref => this.scrollView = ref}
        onContentSizeChange={(contentWidth, contentHeight)=>{        
            this.scrollView.scrollToEnd({animated: true});
        }}>
    </ScrollView>