0

I am attempting to reference a variable in a method in my class and keep running into a NullPointerException. I know it is happening at the variable pbook when it is referenced from the addPerson method. Why is this happening and how could I go about fixing it?

public class Phonebook <T> {

  private LinkedList<T> pbook;

  public T findPerson(T person) {
    for (int i = 0; i < pbook.size(); i++) {
      if (pbook.get(i).equals(person)) {
        return person;
      }
      else
      {
        i++;
      }
    }
    return null;
  }

  public void addPerson(T person) {
    pbook.addFirst(person);
  }

  public void deletePerson(T person) {
    for (int i = 0; i < pbook.size(); i++) {
      if (pbook.get(i).equals(person)) {
        pbook.remove(i);
      }
      else
      {
        i++;
      }
    }
  }


  /**
   * @param args
   */
  public static void main(String[] args){

    try{
     Phonebook<Integer> sspb = new Phonebook<Integer>();
     Phonebook<String> idpb = new Phonebook<String>();
     sspb.addPerson(1234567890);
     idpb.addPerson("Bob");

    }
    catch (Exception e){
      e.printStackTrace();
    }
  }
}
1
  • Note that while in some languages LinkedList<T> pbook; does create a new object, in Java it does not. Commented Jan 28, 2014 at 22:03

4 Answers 4

4

You must add a constructor to instantiate your LinkedList:

public Phonebook() {
    pbook = new LinkedList<T>();
}
Sign up to request clarification or add additional context in comments.

Comments

3

Change:

private LinkedList<T> pbook;

To:

private LinkedList<T> pbook = new LinkedList<T>();

Comments

1

private LinkedList<T> pbook; You don't create a list.

Try this.

private LinkedList<T> pbook = new LinkedList<T>()

Comments

1

1) You can define a constructor e.g. like this.

public Phonebook(LinkedList<T> pbook){
     this.pbook = pbook;
}

Then the calling code will have to set the
pbook when instantiating the Phonebook.

2) You can initialize pbook where you declare it.

private LinkedList<T> pbook = new LinkedList<T>();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.