【发布时间】:2015-10-17 23:25:54
【问题描述】:
我正在研究算法第四版(Sedgewick),并且对一些似乎要求为非静态节点实现静态方法的链表练习感到困惑。例如,
1.3.27 编写一个方法
max(),该方法引用a中的第一个节点 链表作为参数并返回最大键的值 名单。假设所有键都是正整数,如果返回0列表为空。
或
1.3.31 实现一个嵌套类 DoubleNode 来构建双向链表, 其中每个节点都包含对它前面的项目的引用和 列表中它后面的项目(
null,如果没有这样的项目)。然后 为以下任务实现静态方法:在 开始,插入末尾,从开头删除,从开头删除 最后,在给定节点之前插入,在给定节点之后插入,以及 删除给定的节点。
据我了解(并由 SO 回答 here 和 here 确认)这是不可能的。不出所料,如果我尝试在超类中编写静态方法,Eclipse 会报错:
public class DoublyLinkedList<Item> {
public static void insertStart(DoubleNode first) {
// implementation
}
private class DoubleNode {
Item item;
DoubleNode next;
DoubleNode previous;
}
}
(给出错误Cannot make a static reference to the non-static type DoubleNode);或在内部类中:
public class DoublyLinkedList<Item> {
private class DoubleNode {
Item item;
DoubleNode next;
DoubleNode previous;
public static void insertStart(DoubleNode first) {
// implementation
}
}
}
(给出错误The method insertStart cannot be declared static; static methods can only be declared in a static or top level type)。
我可以将所需的方法编写为DoublyLinkedList 类的实例方法,这对我来说似乎是最自然的。
但是,我觉得我可能在这里错过了一些重要的事情。作者明确指出方法应该是静态的,并且还建议将第一个节点的引用作为参数(这对于实例方法来说是不必要的,因为该类将具有第一个节点的实例变量)。我错过了什么?
【问题讨论】:
标签: java static linked-list static-methods inner-classes