简体   繁体   English

java中的列表打印列表

[英]List of List Printing in java

I have the below list:我有以下清单:

[10, 20, [44, 55], [[777, 888]]]

I wanna print like below (Index.Value):我想打印如下(Index.Value):

0.10
1.20
2.0.44
2.1.55
3.0.0.777
3.0.1.888
public static void main(String a[]) {
    List<Object> list1 = new ArrayList<>();
    list1.add(10);
    list1.add(20);

    List<Object> list2 = new ArrayList<>();
    list2.add(44);
    list2.add(55);

    List<Object> list3 = new ArrayList<>();
    List<Object> list4 = new ArrayList<>();
    list4.add(777);
    list4.add(888);

    list3.add(list4);

    list1.add(list2);
    list1.add(list3);

    System.out.println(list1);
    print(list1, "");
}

static void print(List<Object> list, String s) {
    for (int i = 0; i < list.size(); i++) {
        if (list.get(i) instanceof Integer) {
            System.out.println(s + i + "." + list.get(i));
        } else {
            s = s + i + ".";
            print((List<Object>)list.get(i),s);
        }
    }
}

Above code is printing like below:上面的代码打印如下:

0.10
1.20
2.0.44
2.1.55
2.3.0.0.777
2.3.0.1.888

I know there is something wrong with my code.我知道我的代码有问题。 Do we have any other way to handle this?我们有没有其他办法来处理这个问题? Can anyone help me out?谁能帮我吗?

When you process the 3rd element of your outer list, you append "2."当您处理外部列表的第三个元素时,您会附加“2”。 to s and assign the result to s .s并将结果分配给s

Then, when you process the 4th element of your outer list, you append "3."然后,当您处理外部列表的第 4 个元素时,附加“3”。 to s and assign the result to s , so now s contains "2.3."s并将结果分配给s ,所以现在s包含“2.3”。 instead of the desired "3."而不是所需的“3”。 which should be passed to the recursive call.应该传递给递归调用。

You can avoid that if instead of assigning anything to s , you'd just pass s + i + "."如果不是为s分配任何内容,而只需传递s + i + "." ,则可以避免这种情况s + i + "." to the recursive call.到递归调用。

Change改变

s = s + i + ".";
print((List<Object>)list.get(i),s);

to

print((List<Object>)list.get(i),s + i + ".");

Now the output will be:现在输出将是:

0.10
1.20
2.0.44
2.1.55
3.0.0.777
3.0.1.888

The full corrected method:完整修正方法:

static void print(List<Object> list, String s) {
    for (int i = 0; i < list.size(); i++) {
        if (list.get(i) instanceof Integer) {
            System.out.println(s + i + "." + list.get(i));
        } else {
            print((List<Object>)list.get(i),s + i + ".");
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM