正确的方法将对象添加到一个ArrayList对象、正确、方法、ArrayList

由网友(正在删除)分享简介:我试图将一个对象添加到一个ArrayList,但是当我查看数组列表的结果,它一直一遍又一遍地将相同的对象到ArrayList。我想知道什么是正确的方式来实现,这将是。I am trying to add an object to an arraylist but when I view the results of...

我试图将一个对象添加到一个ArrayList,但是当我查看数组列表的结果,它一直一遍又一遍地将相同的对象到ArrayList。我想知道什么是正确的方式来实现,这将是。

I am trying to add an object to an arraylist but when I view the results of the array list, it keeps adding the same object over and over to the arraylist. I was wondering what the correct way to implement this would be.

    public static ArrayList<Person> parsePeople(String responseData) {
    ArrayList<Person> People = new ArrayList<Person>();
    try {

        JSONArray jsonPeople = new JSONArray(responseData);
        if (!jsonPeople.isNull(0)) {
            for (int i = 0; i < jsonPeople.length(); i++) {
                People.add(new Person(jsonPeople.getJSONObject(i)));
            }

        }

    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (Exception e) {

    }

    return People;
}

我有双重检查我的JSONArray数据并确保它们不重复。它似乎保持遍地将第一对象

I have double checked my JSONArray data and made sure they are not duplicates. It seems to keep adding the first object over and over.

推荐答案

可能出现了与responseData字符串或构造函数的问题。

There is either a problem with the responseData string or the constructor.

如果该类收到响应数据对象,如下所示

If the class receives a response Data object that looks like the following

String responseData = 
"[{ 
"first_name" : "fred" , 
"last_name" : "Nobody"  
}, 
{ 
"first_name" : "John" , 
"last_name" : "Somebody"  
}]";

那么你联系的类应为

Then your Contact class should look like

public class Contact {
    String fname;
    String lname;

    public Contact(JSONObject obj){
        System.out.println(obj);
        try {
            fname = (String)obj.get("first_name");
            lname = (String)obj.get("last_name");
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
//get and set methods
}

应该没有理由根据你的逻辑有相同的记录显示了两次。请确保您的JSON字符串格式正确进来。我建议增加的应用程序,确定每一个步骤的更多的System.out或者Log4j的要求。通过与调试会话的应用程序最坏情况下的一步。

There should be no reason based on your logic to have the same record show up twice. Make sure your JSON string has the correct format coming in. I would suggest adding more System.out or Log4j calls in the application to determine every step. Worst case step through the application with a debug session.

PS - 我建你的应用程序中加入上述code和它工作得很好。所以,你必须在添加元素到ArrayList正确的把握。你也可以告诉你如何打印阵列背出来?也许这个问题是存在的。

PS - I built you app by adding the above code and it worked fine. So you have the grasp on adding the elements to the ArrayList properly. Could you also show how you print the array back out? Maybe the issue is there.

阅读全文

相关推荐

最新文章