2
\$\begingroup\$

I'm working my way through The Java Programming Language, 4th edition. This is exercise 2.2:

Write a LinkedList class that has a field of type Object and a reference to the next LinkedList element in the list.

Is this an adequate solution? Is there a more efficient way to build up a test list for this example?

class Node {
    private Object data;
    private Node next;

    public Node(Object data) {
        this(data, null);
    }

    public Node(Object data, Node next) {
        this.data = data;
        this.next = next;
    }

    public void setData(Object data) {
        this.data = data;
    }

    public Object getData() {
        return data;
    }

    public Node getNext() {
        return next;
    }
}

class LinkedListTest {

    public static void main(String[] args) {

        Node node3 = new Node("puke");
        Node node2 = new Node("vomit", node3);
        Node node1 = new Node("blah", node2);

        Node node = node1;
        while (node != null) {
            System.out.println("Data = " + node.getData());
            node = node.getNext();
        }
    }
}
\$\endgroup\$

1 Answer 1

4
\$\begingroup\$

I would say it is an adequate solution. The product may not feel very useful yet, but it's probably not supposed to be. In some sense, the exercise is formulated ambiguously. Your Node class can be used to construct linked lists and as such is a building block of instantiated linked lists. However, I would not consider that a LinkedList implementation. A LinkedList implementation would consist of a wrapper class that hides this Node from the user and allows you to say thinks like

List list = new LinkedList();
list.add("foo"); 
list.add("bar"); 
list.remove("foo"); 
int index = list.indexOf("bar");
etc.

It may seem somewhat unsatisfactory that you have to construct your test list so clumsily, but ease of use wasn't a goal of the exercise ;)

\$\endgroup\$
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.