I got a problem as I have been recently trying to write my own "library" with different well-known data structures such as linked lists, trees, tries, heaps, etc.

Sadly, I got stuck while coding the first one (the linked list). For that, I wrote a "Node" class (separate file), and a "Linked List" class, which "extends" the "Node" class (in order to use it as a reference object). Long story short, here is my code so far:

"Node.java"

package helper;

public class Node<T> {
    private T value;
    private Node<T> next;

    protected Node(T newValue) {
        value = newValue;
        next = null;
    }

    protected void printNode() {
        System.out.print("{" + value + "} ");
    }
}

"LinkedList.java"

package source;

import helper.Node;

public class LinkedList<T> extends Node<T> {
    private Node<T> head, current;

    protected LinkedList(T newValue) {
        super(newValue);
        // TODO Auto-generated constructor stub
    }
}

Obviously, I'm not even half-way done, but what I don't understand, is why on C++ (coded in C++ for like 4 years and only recently started java) I don't have to define a constructor which makes a "super()" call, like calling the constructor of the derived class, but on Java, I have to do that..

All I want to do, is use the "Node" class to create "Node" objects in the "LinkedList" class.. I don't want the "LinkedList" constructor to call the "Node" constructor (we should have an empty Linked List after constructor is called).

Sorry if I sound a little confusing, but hope you understood what I wanted to say. Thanks in advance.

EDIT: Please don't tell me to use the Java built-in libraries, as I am doing this just for practice.

有帮助吗?

解决方案

Your LinkedList structure should contain a Node, not be a Node. In Java, you always have to explicitly call the super constructor if a no-arg constructor is not provided. Whenever you create an object, all superclasses constructors are called in order from most generic, to most specific so in this case, the Node constructor would be called first before the LinkedList constructor.

其他提示

You should prefer composition over inheritance in this case. Right now your LinkedList isA Node and since Node has just single constructor that takes value, you have to call super(value).

Also you can use LinkedList from java.util package (don't reinvent the wheel here).

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top