0

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!

2 Answers 2

4

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>();
Sign up to request clarification or add additional context in comments.

Comments

4

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

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

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.