java - 如何将循环中的值放入数组列表中?

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

那么我该怎么做呢?

最佳答案

将两个属性包装在一个新对象中,并将该对象插入数组列表中。

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/

相关文章:

java - Android 在注册推送通知期间崩溃

Android NDK 尝试使用 sdk/ndk-bundle/sources/cxx-STL/gnu-libstdc++ 进行构建/但 gnu-libstdc++ 不存在

android - 更改粗体 html 文本的文本颜色

arrays - 声明具有特定类型但任意维数的数组

javascript - 在 JavaScript 中使用数组作为名称对输入元素的值进行计数

Java JDBC : Do I need to loop ResultSet when query returns single row?

java - JPA + hibernate : How to define a constraint having ON DELETE CASCADE

java - java中的线程争用

java - 将鼠标位置分派(dispatch)给 JList 的自定义单元格渲染器中的组件

c - 使用 strcmp(char*,char*) 时出现关于 char* 的错误