Ctech45
Ctech45

Reputation: 496

Null Pointer Exception upon referencing variable

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();
    }
  }
}

Upvotes: 0

Views: 88

Answers (4)

peter.petrov
peter.petrov

Reputation: 39437

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>();

Upvotes: 1

Happy
Happy

Reputation: 1855

You must add a constructor to instantiate your LinkedList:

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

Upvotes: 4

Salih Erikci
Salih Erikci

Reputation: 5087

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

Try this.

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

Upvotes: 1

barak manos
barak manos

Reputation: 30126

Change:

private LinkedList<T> pbook;

To:

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

Upvotes: 3

Related Questions