如何将值从我的循环中放入arraylist?

时间:2013-12-20 19:51:55

标签: java android arrays

我有这段代码

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)。

那我怎么能这样做?

1 个答案:

答案 0 :(得分:2)

将两个属性包装在一个新Object中,并将该对象推送到arraylist中。

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));
}