What is the correct implementation of a DoublyLinkedList class that extends LinkedList in Java?

StackOverflow https://stackoverflow.com/questions/8735852

質問

I have my own custom LinkedList class that has a pointer to the first Node in the list. I now need to create a DoublyLinkedList class. The only difference between the DoublyLinkedList and the LinkedList is that the DoublyLinkedList uses DoubleNodes instead of Nodes. My DoubleNode class extends the Node class.

What is the correct way create a DoublyLinkedList that extends LinkedList?

Would have have to constantly cast DoubleNodes to Nodes? Or is there a simpler way that I'm just missing?

Thanks for any help.

役に立ちましたか?

解決 2

Well I managed to figure this out on my own.

As it turns out, the only method that needs to change for DoublyLinkedList is the add method. Here's my DoublyLinkedList add method:

public void add(Object obj){
        DoubleNode newNode = new DoubleNode(obj);
        newNode.setPrev(getLast());
        super.add((Node)newNode);
    }

By creating a new DoubleNode and then casting it to a Node, I am able to keep most methods the same. If I need to access the DoubleNode's prev pointer, I can downcast the Node as needed.

他のヒント

Use Generics - having your node type as a parameterized type on your LinkedList.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top