Static Methods for Inner Class Operations

I am working on algorithms for the fourth edition (Sedgewick) and am confused by some linked list exercises that seem to be asking to implement static methods for non-static nodes. For instance,

1.3.27 Write a method max()that refers to the first node in the linked list as an argument and returns the maximum key value to the list. Suppose all keys are positive integers and return 0if the list is empty.

or

1.3.31 Implement the nested DoubleNode class to create doubly linked lists, where each node contains a link to the element preceding it and the element following it in the list ( nullif there is no such element). then implement static methods for the following tasks: insert at the beginning, insert at the end, remove from the beginning, remove from the end, insert before the given node, insert after the given node and delete the given node.

As I understand it (and confirmed SO answers here and here ), this is not possible. As expected, Eclipse gives errors if I try to write a static method in a superclass:

public class DoublyLinkedList<Item> {

    public static void insertStart(DoubleNode first) {
        // implementation
    }

    private class DoubleNode {
        Item item;
        DoubleNode next;
        DoubleNode previous;

    }
}

(gives an error Cannot make a static reference to the non-static type DoubleNode); or in the inner class:

public class DoublyLinkedList<Item> {

    private class DoubleNode {
        Item item;
        DoubleNode next;
        DoubleNode previous;

        public static void insertStart(DoubleNode first) {
            // implementation
        }
    }
}

(gives an error The method insertStart cannot be declared static; static methods can only be declared in a static or top level type).

DoublyLinkedList, .

, , - . , , node ( , node), ?

+4
1

static. , DoubleNode :

// This will compile
public class DoublyLinkedList<Item> {

    public static <T> void insertStart(DoublyLinkedList<T> list, DoubleNode<T> first) {
        // implementation
    }

    private static class DoubleNode<E> {
        E item;
        DoubleNode<E> next;
        DoubleNode<E> previous;

    }
}

: , ( E). , DoubleNode DoublyLinkedList, , Item.

-, ( "<T>" ), . :

public static void insertStart(DoublyLinkedList<?> list, DoubleNode<?> first) {
    ...
}

, , JDK LinkedList:

// Source : Oracle JDK 1.7.0_67 lib - inside LinkedList class
private static class Node<E> {
     E item;
     Node<E> next;
     Node<E> prev;

    Node(Node<E> prev, E element, Node<E> next) {
       this.item = element;
       this.next = next;
       this.prev = prev;
    }
}

, , ; . Sedgewick, , , ;)

+4

All Articles