我有这个代码
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)。
那么我该怎么做呢?
最佳答案
将两个属性包装在一个新对象中,并将该对象插入数组列表中。
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));
}
关于java - 如何将循环中的值放入数组列表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20710986/