Skip to content

Instantly share code, notes, and snippets.

@sergchil
Created December 4, 2017 18:07
Show Gist options
  • Save sergchil/2980743f1bdca72aec0b2f3ac8173b90 to your computer and use it in GitHub Desktop.
Save sergchil/2980743f1bdca72aec0b2f3ac8173b90 to your computer and use it in GitHub Desktop.
Flatten nested arrays
public static void main() {
Object[] array1 = new Object[]{3}; // [3]
Object[] array2 = new Object[]{1, 2, array1}; // [ 1, 2, [3] ]
Object[] nestedArrays = new Object[]{array2, 4, null}; // [ [ 1, 2, [3] ] 4 ]
ArrayList<Integer> flatOutput = new ArrayList<>();
try {
flatten(nestedArrays, flatOutput);
System.out.println("flatOutput = " + flatOutput);
} catch (NullPointerException e) {
System.err.println("something goes wrong");
e.printStackTrace();
}
}
public void flatten(Object[] nestedArrays, ArrayList<Integer> flatOutput) throws NullPointerException {
if (nestedArrays == null) {
throw new NullPointerException("Input array should not be null");
}
if (flatOutput == null) {
throw new NullPointerException("Output array should not be null");
}
for (Object element : nestedArrays) {
// of course int is not derived from Object, int this case JVM uses autoboxing to store int as Integer
if (element instanceof Integer) {
// is number
flatOutput.add((int) element);
} else {
// is array
flatten((Object[]) element, flatOutput);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment