Darkhail Darkhail - 1 month ago 16
Java Question

Insert method for a linked list

Alright so I am working on making a linked list and I have to insert each object I receive into the list and have them point to each other. Right now I have:

public void insert(Object o) {
curr.setNext(new Link(curr.getItem(),curr.getNext()));
curr.setItem(o);
}


I only seem to be throwing NullPointerExceptions though when I test this. This is my first test for it by the way:

public void testIfInsertMakesAList() {
String a = "a";

LList x = new LList();

x.insert(a);

String xExpected = "a";

assertEquals("insert does not insert one object in a list", xExpected, x.get());
}


Any advice would be most helpful.

Answer

Try this.

public void insert(Object o) {
    curr = new Link(o, curr);
}
Comments