Reputation: 567
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?
Upvotes: 1
Views: 168
Reputation: 1
OR you can change like this
public FriendList() {
ArrayList<String> friendList = new ArrayList<String>();
}
to
public FriendList() {
this.friendList = new ArrayList<String>();
}
Upvotes: 0
Reputation: 1285
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
Upvotes: 0
Reputation: 2300
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>();
}
Upvotes: 2
Reputation: 19284
You're hiding friendList
field.
Use instead:
public FriendList() {
friendList = new ArrayList<String>();
}
In your constructor, you instantiate a local variable friendList
.
Upvotes: 7
Reputation: 393791
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>();
}
Upvotes: 10