有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java将对象添加到嵌套for循环内的arraylist

我试图将JSON数组循环到数组列表类别和嵌套的Arraylist子类别

我的问题是,我的列表不仅会填充第一个子类别数据,还会填充第二个子类别数据

例如,我想要:

1st category [Apple, Kiwi] 
2nd category [Mango, Banana]

但是我得到的是

第二类填充为[Apple,Kiwi,Mango,Banana]

ArrayList<Category> categoryName=new ArrayList<Category>();
ArrayList<ArrayList<SubCategory>> subCategoryName = new ArrayList<ArrayList<SubCategory>>();
ArrayList<Integer> subCategoryCount = new ArrayList<Integer>(); 

ArrayList<SubCategory> subCategoryMatches = new ArrayList<SubCategory>();
try {
    // Parsing json array response
    // loop through each json object

    for (int i = 0; i < response.length(); i++) {

        JSONObject allCategory = (JSONObject) response
                .get(i);

        int id = allCategory.getInt("mcatid");
        String description = allCategory.getString("description");

        Category categoryDetails = new Category();
        categoryDetails.setCatCode(id);
        categoryDetails.setCatName(description);
        category_name.add(categoryDetails);

        //Log.i(TAG, String.valueOf(description));

        JSONArray  allSubCategory = allCategory
                .getJSONArray("Subcatergory");

        for (int j = 0; j < allSubCategory.length(); j++) {

            JSONObject jsonObject = allSubCategory.getJSONObject(j);

            String subCatId = jsonObject.getString("id");

            String subDescription = jsonObject.getString("description");

            // retrieve the values like this so on..

            //Log.i(TAG, String.valueOf(subDescription));


            SubCategory subCategoryMatch = new SubCategory();
            subCategoryMatch.setSubCatName(subDescription);
            subCategoryMatch.setSubCatCode(subCatId);
            subCategoryMatches.add(subCategoryMatch);

        }

        subcategory_name.add(subCategoryMatches);
        subCatCount.add(subCategoryMatches.size());
    }

共 (1) 个答案

  1. # 1 楼答案

    您将添加到相同的subCategoryMatches列表引用中,因此您将获得一个对象中的所有数据

    在添加到循环之前,您需要一个新列表

    ArrayList<SubCategory> subCategoryMatches;
    
    try {
        // Parsing json array response
        // loop through each json object
    
        for (int i = 0; i < response.length(); i++) {
            ...
    
            // New list
            subCategoryMatches = new ArrayList<SubCategory>();
    
            // Loop and add
            for (int j = 0; j < allSubCategory.length(); j++) {
                ...
                subCategoryMatches.add(subCategoryMatch);
            }
    
            // Add new list to outer list
            subcategory_name.add(subCategoryMatches);
        }
    }