I am currently studying up on linked lists in Java. I have a sample program that works as expected for certain input, and not at all for other input.
//Constructor in class List of People
ListOfPeople() {
Person listHead = new Person("LIST HEAD");
personList = listHead;
lastPerson = listHead;
numberPeople = 0;
}
//Adds person to the beginning of the list
public void addFirst(Person newP) {
newP.next = personList.next;
personList.next = newP;
numberPeople++;
}
//Adds person to the end of the list
public void addLast(Person lastP) {
lastPerson.next = lastP;
lastPerson = lastP;
numberPeople++;
}
For the Person class, I have the following code:
//From the Person class
String name;
Person next;
Person(String n) {
name = n;
next = null;
}
Suppose I add two different people to the beginning of the list:
Person mulan = new Person("Mulan");
myFriends.addFirst(mulan);
Person mushu = new Person("Mushu");
myFriends.addFirst(mushu);
Then, the code works without problems. And I get the output: "Mushu, Mulan". HOWEVER, if I add one person at the beginning of the list, and another at the end, I get a NullPointerException. If I try to invoke the addLast(String name) method on both Person objects, there seems to be no problem.
Any tips are highly appreciated!
ListOfPeopleclass and the exact point where the NPE is thrown. NPEs at this level can be easily spotted runnning a debugger, you should try to use it. That said, think about what should happen tolastPersonif you add aPersonwithaddFirstto an empty list...... And I get the output: "Mushu, Mulan".please show how do you fetch this names