Given a nested list of strings (which may contain other nested lists), print the contents of the list and the corresponding depth.
Here is my solution:
private static void dumpList(String string, List l) {
int n = l.size();
for (int i = 0; i < n; i++) {
if(l.get(i) instanceof String){
System.out.println(string+i + " " + l.get(i));
}
if(l.get(i) instanceof List){
dumpList(string+i, (List)l.get(i));
}
}
}
Here is main()
:
public static void main(String[] args) {
String s = "Foo";
List l = new ArrayList();
ArrayList<String> a = new ArrayList<String>();
ArrayList<String> b = new ArrayList<String>();
//ArrayList<String> c = new ArrayList<String>();
a.add("a");
a.add("b");
a.add("c");
b.add("eggs");
l.add("a string");
l.add(a);
l.add("spam");
l.add("eggs");
dumpList("Foo", l);
}
My output:
Foo0 a string Foo10 a Foo11 b Foo12 c Foo2 spam Foo3 eggs
I am not that much interested in naming of the variables, but of formatting of the output. Should I use StringBuilder
instead of the +
operator? Should I print it differently?
List<Object>
so you get no warnings. \$\endgroup\$