user3488736
user3488736

Reputation: 109

NullPointerException in a simple ArrayList.add function?

I'm getting used to java again and was experimenting with collections. I have the following very basic code but I can't seem to find the reason why I get an Nullpointer exception:

   import java.util.*;

    public class Event

{
    private ArrayList<String> fans;

    public Event()
    {
        ArrayList<String> fans = new ArrayList<String>();
    }

    public void registerUser(String user)
    {    
        fans.add(user);
    }
}

Thanks in advance everyone!

Upvotes: 0

Views: 54

Answers (2)

rgettman
rgettman

Reputation: 178263

You've initialized a local fans in your constructor, so your instance variable fans is not explicitly initialized, so it's still null in registerUser.

Change

ArrayList<String> fans = new ArrayList<String>();

to

fans = new ArrayList<String>();

Upvotes: 4

Alexis C.
Alexis C.

Reputation: 93842

You are shadowing your class field in your constructor. Remove the datatype declaration.

public Event(){
    fans = new ArrayList<String>();
}

Upvotes: 4

Related Questions