2014-10-30 60 views
1
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(); 
    } 
} 

我已經嘗試了一些東西,但似乎無法設法將字符串添加到數組列表中。任何想法,爲什麼這可能是?當我嘗試向我的ArrayList添加字符串時,爲什麼我的類會導致'NullPointerException'?

回答

10

您的構造函數初始化一個本地變量ArrayList,因此您的friendList成員永遠不會初始化。 當您嘗試使用其他方法訪問未初始化的成員時,您會收到NullPointerException

變化

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

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

甚至更​​好的改變:好友列表=新的ArrayList < >()如果你使用Java 1.7 – 2014-10-30 14:57:23

+0

@DavidSoroko爲什麼你認爲這更好?僅僅是因爲你不必再輸入6個字母? – spoko 2014-10-30 15:02:48

+0

其中之一是資本;-)。看看這個[鏈接] http://stackoverflow.com/questions/4166966/what-is-the-point-of-the-diamond-operator-in-java-7 可以改變'private ArrayList friendList '只能在一個地方使用私有ArrayList friendList',所有東西都會編譯。 – 2014-10-30 15:19:27

7

你躲在friendList場。

使用,而不是:

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

在構造函數,實例化一個局部變量friendList

2

您不是初始化instace成員,而是創建並設置構造函數的本地列表。它死於構造函數的範圍之外。

所以基本上你正在嘗試添加字符串到尚未創建的列表。

從這篇文章要注意的另一件事是Java將所有未初始化的對象/實例設置爲空因此異常。改變這種

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

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

您在構造函數中創建的friendsList列表是隱藏了全球friendsList一個局部變量。所以,現在解決您的問題,只需更換線

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

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

在這之後,你必須看看variable scope principles.的大多是常見的所有編程語言

0

或者你可以這樣

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