2013-12-20 22 views
0

我有這樣的代碼如何將值從我的循環中放入arraylist中?

for (int i = 0; i < friendslocations.length(); i++) 
{ 
    JSONObject c = friendslocations.getJSONObject(i); 

    String friendName = c.getString(TAG_FRIENDNAME); 
    System.out.println("friend name " + friendName); 

    String friendLocation = c.getString(TAG_LOCATION); 
    System.out.println("friendlocation" + friendLocation); 
} 

,保存着印刷我我想要的值。

但我需要知道如何將來自此循環(friendname和friendloaction)的值放入數組列表中,其中每個索引包含此(friendname,friendlocation)。

那麼我該如何做到這一點?

+0

你剛纔在10分鐘前提問這個問題。首先創建一個數組。然後在循環中將這些項目添加到數組中。 – user1336827

+0

如果你想保持兩個字段彼此創建一個類,然後創建一個類'Arraylist' –

回答

2

將你的兩個屬性包裝在一個新的對象中,並將該對象推入數組列表。

class FriendData { 
    public String friendName; 
    public String friendLocation 
    public FriendData(String friendName, String friendLocation) { 
     this.friendName=friendName; 
     this.friendLocation=friendLocation; 
    } 

    public String toString() { 
     return "friendName="+friendName+" friendLocation="+friendLocation; 
    } 
} 

List<FriendData> friendsList = new ArrayList<>(); 
for (int i = 0; i < friendslocations.length(); i++) { 
    JSONObject c = friendslocations.getJSONObject(i); 
    String friendName = c.getString(TAG_FRIENDNAME); 
    String friendLocation = c.getString(TAG_LOCATION); 
    friendsList.add(new FriendData(friendName, friendLocation)); 
} 
+0

如果你打算把它們作爲參數,你可能應該在構造函數中設置你的屬性值 – dataNinja124

+0

@ dataNinja124: 。修正了噓聲! –

相關問題