简体   繁体   中英

Why does my class cause 'NullPointerException' when I try to add a string to my ArrayList?

import java.util.ArrayList;

public class FriendList {

    private ArrayList<String> friendList;

    public FriendList() {
        ArrayList<String> friendList = new ArrayList<String>();
    }

    public void addFriend(String friend) {
        friendList.add(friend);
    }

    public String getFriends() {
        return friendList.toString();
    }
}

I've tried a few things but can't seem to manage to add strings to the array list. Any ideas why this might be?

Your constructor initializes a local ArrayList variable, so your friendList member is never initialized. When you try to access the uninitialized member in other methods, you get a NullPointerException .

Change

public FriendList() {
    ArrayList<String> friendList = new ArrayList<String>();
}

to

public FriendList() {
    friendList = new ArrayList<String>();
}

You're hiding friendList field.

Use instead:

public FriendList() {
    friendList = new ArrayList<String>();
}

In your constructor, you instantiate a local variable friendList .

You are not initializing the instace member but creating and setting a list local to the constructor. It dies outside the scope of the constructor.

So basically you are trying to add strings to a list that has not been created yet.

One other thing to note from this post is Java sets all it uninitialized objects/instances to null Hence the Exception . Change this

public FriendList() {
    ArrayList<String> friendList = new ArrayList<String>();
}

to

public FriendList() {
    friendList = new ArrayList<String>();
}

The friendsList list that you create inside the constructor is a local variable that hides the global friendsList. So, to solve your problem right now, just replace the line

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

with

   this.friendList = new ArrayList<String>();

After that, you have to take a look at variable scope principles. The most of them are common for all programming languages

OR you can change like this

public FriendList() {
    ArrayList<String> friendList = new ArrayList<String>();
}
to
public FriendList() {
    this.friendList = new ArrayList<String>();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM