In: Computer Science
(Java) Building a Doubly Linked List off of an interface I am
having trouble with these two methods
@Override public void add(T newEntry) { DoubleLinkedNode newNode = new DoubleLinkedNode(newEntry); if (!isEmpty()) { } if (isEmpty()) { first = newNode; last = newNode; } else { last.setNextNode(newNode); newNode.setPreviousNode(last); last = newNode; } // length++; numElements++; } @Override public void add(int newPosition, T newEntry) { DoubleLinkedNode newAdder = new DoubleLinkedNode(newEntry); if ((newPosition >= 0) && (newPosition <= numElements)) { numElements++; if (newPosition == 0) { add(newEntry); } else if (newPosition >= getLength() + 1) { DoubleLinkedNode previousNode = getNodeAt(newPosition - 1); DoubleLinkedNode NextNode = previousNode.getNextNode(); newAdder.setNextNode(NextNode); newAdder.setPreviousNode(previousNode); previousNode.setNextNode(newAdder); NextNode.setPreviousNode(newAdder); } else if (newPosition == getLength()) { DoubleLinkedNode previousNode = getNodeAt(newPosition - 1); previousNode.setNextNode(newAdder); newAdder.setPreviousNode(previousNode); last = newAdder; } } else { throw new IndexOutOfBoundsException(""); } } I cannot figure out how to get the add newEntry and other add method to work All the Method calls do what you'd think they'd do
The code snippet shown here represents function overloading rather than function overriding.
Function overriding requires both functions to have exactly the same function prototype (access specifier, return type, name and parameter list). And the functions must be present in two different classes, one of whom inherits the other.
Function overloading, on the other hand, is two or more functions having the same name but different parameter lists.
Which of the overloaded functions is to work for a given function call is determined by the compiler at compile time. For example, if there is a call,
add(entry); //entry is of type T
the function public void add (T newEntry) is invoked. Whereas for a function call like
add(pos, entry); //pos is of type integer and entry is of type T
the function public void add (int newPosition, T newEntry) is invoked.
So, to make the functions work as desired, they have to be invoked with the correct required parameters. The main() function, for example, may be written as follows:
public static void main(String args[])
{
T entry;
int pos=5;
add(pos, entry);
}
This will add a node at position 5 of the doubly linked list with the specified contents.