What is the correct implementation of a DoublyLinkedList class that extends LinkedList in Java?
-
28-03-2021 - |
Question
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 DoubleNode
s instead of Node
s. My DoubleNode
class extends the Node
class.
What is the correct way create a DoublyLinkedList
that extends LinkedList
?
Would have have to constantly cast DoubleNode
s to Node
s? Or is there a simpler way that I'm just missing?
Thanks for any help.
Solution 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.
OTHER TIPS
Use Generics - having your node type as a parameterized type on your LinkedList
.