Reputation: 83
I have the below list:
[10, 20, [44, 55], [[777, 888]]]
I wanna print like below (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?
Upvotes: 0
Views: 117
Reputation: 393846
When you process the 3rd element of your outer list, you append "2." to s
and assign the result to s
.
Then, when you process the 4th element of your outer list, you append "3." to s
and assign the result to s
, so now s
contains "2.3." instead of the desired "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 + "."
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 + ".");
}
}
}
Upvotes: 2