Question

The more I google this the more confused I'm getting.

I'm bringing in a list of names of unknown length with some other details in from a CSV which I then need to turn into Person objects and store in a list called people which is the instance variable for the class Club, a list of its members basically.

This is a very simplified version of something more complex I need to do in which I need to while loop through a file creating objects for each line which I then need to add to a list collection.

I keep getting a nullPointerException error when I run my code though and I'm stumped how to avoid it. I'm guessing that my variable p when I create the new object would need to change on each loop but I don't think it's possible to change variables dynamically is it?

Can't think how I can commit the object to the collection with a valid non null reference each time. Would be very grateful for any help. I've tried to cut out all the unnecessary stuff in the code below.

Thank you

   //class arraylist instance variable of class "Club"
   private ArrayList<Person> people;

   //class constructor for Club
   public Club()
   {List<Person> people = new ArrayList<>();}

   public void readInClubMembers()
   {
      //some variables concerning the file input
      String currentLine;
      String name;
      String ageGroup;
      while (bufferedScanner.hasNextLine())
      {
         //some lines bringing in the scanner input from the file
         name = lineScanner.next();
         ageGroup = "young";
         Person p = new Person(); // i guess things are going wrong around here
         people.add(p);
         p.setName(name);
         p.setAgeGroup(ageGroup);
      }
   }
Was it helpful?

Solution

Remove the List<Person> before people = … inside the constructor, otherwise you are declaring a new local variable people inside the constructor shadowing the field people (which is then never used). This leaves the class field uninitialized (null) and then causes the NPE.

What you want instead is initializing the field people:

public Club() {
    // you can also use "this.people = …" to be explicit
    people = new ArrayList<>();
}

To show the difference:

class Example {
    private int myNumber;

    public Example() {
        myNumber = 42; // sets the field of the class
        int myNumber = 1337; // declares a new local variable shadowing the class field
        myNumber = -13; // accesses the object in the closest scope which is the local variable
        this.myNumber = 0; // explicitly accesses the class field
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top