For homework, I am working on writing a LinkedList class, that replaces the LinkedList methods. I'm working on the "set" method.
Here's what I have so far for the set() method. It takes in int index
and X item
as parameters. The head of the node is in a variable called first
. (The whole class is genericized.)
Node<X> p = new Node<X>();
if(index < 0 || index > size()-1){
throw new Bonfire();
}
int count = 0;
while(count != index){
p = p.next;
count++;
}
if(count == index){
p.item = item;
}
Node class:
public class Node<T>
{
T item;
Node<T> next;
}
When I go to run my code against some test code that I have, it fails the test.
Test Code:
LList<String> b = new LList<String>();
b.add("Hello");
b.add("Bye");
b.set(0, "Bonjour");
assertEquals("Bonjour", b.get(0));
Failed test Reason: org.junit.ComparisonFailure: expected:<[Bonjour]> but was:<[Hello]>
(add(), size(), and get() methods are working correctly.)
So my question is, how do I get this to set the element correctly? From this code, and from why it's failing the test, it looks like it's not setting anything at all. If you need any extra information from me, do not hesitate to ask me. Appreciate the help. Thanks!
1 Answer 1
All I needed to do was change Node<X> p
to make it Node<X> p = first;
.
Node
? Don’t you have the head stored in a field?Node
, which won’t have any links to any otherNode
s. Does your class have any fields?add()
method.