Another advantage of this approach is, that you are separating the collection of the data from the printing of the data. It would be easy to change the print command with for example a command to print to file later on.
Because you are using recursion, you would need to pass it as a parameter:
private static void dumpList(String string, List l, StringBuilder sb) {
int n = l.size();
for (int i = 0; i < n; i++) {
if (l.get(i) instanceof String) {
sb.append("\n").append(string).append(i).append(" ").append(l.get(i)).append("\n");
// or Version 2:
// sb.append(string + i + " " + l.get(i) + "\n");
}
if (l.get(i) instanceof List) {
dumpList(string + i, (List) l.get(i), sb);
}
}
}
(The second version is a bit more readable, while the first version might be faster, depending on the Java implementation)