如何将以下数据转换为LOOP

时间:2019-03-23 23:06:29

标签: java android arraylist

我正在尝试将以下内容转换为循环,但是我白费了一切 我希望有人帮我将这种类型的数据转换成循环。

ArrayList<String> parentList = new ArrayList<>();
        ArrayList<ArrayList> childListHolder = new ArrayList<>();

        parentList.add("Parent1");
        parentList.add("Parent2");
        parentList.add("Parent3");

        ArrayList<String> childNameList = new ArrayList<>();
        childNameList.add("Child1");
        childNameList.add("Child2");
        childNameList.add("Child3");

        childListHolder.add(childNameList);

        childNameList = new ArrayList<>();
        childNameList.add("Child4");
        childNameList.add("Child5");
        childNameList.add("Child6");

        childListHolder.add(childNameList);

        childNameList = new ArrayList<>();
        childNameList.add("Child7");
        childNameList.add("Child8");
        childNameList.add("Child9");

        childListHolder.add(childNameList);

2 个答案:

答案 0 :(得分:1)

这里不需要循环,也不要使用ArrayList作为原始类型,而希望使用List接口。使用Arrays.asList(T...)生成您的List。喜欢,

List<List<String>> childListHolder = new ArrayList<>();
List<String> parentList = Arrays.asList("Fruits & Vegetables", 
        "Beverages & Health", "Home & Kitchen");
childListHolder.add(Arrays.asList("Apple", "Mango", "Banana"));
childListHolder.add(Arrays.asList("Red bull", "Maa", "Horlicks"));
childListHolder.add(Arrays.asList("Knife", "Vessels", "Spoons"));

答案 1 :(得分:0)

与循环等效的代码是这样的:

ArrayList<String> parentList = new ArrayList<>();
ArrayList<ArrayList> childListHolder = new ArrayList<>();

for (int i = 1; i <= 3; i++) {
    parentList.add("Parent" + i);

    ArrayList<String> childNameList = new ArrayList<>();
    for (int j = 1; j <= 3; j++) {
        childNameList.add("Child" + (3 * (i - 1) + j));
    }
    childListHolder.add(childNameList);
}