Created
April 6, 2016 13:07
-
-
Save asanand3/017f944299ebe6623b784d5d11a6602a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package test; | |
import java.util.ArrayList; | |
import java.util.Arrays; | |
import java.util.List; | |
public class FlattenArray { | |
public static void main(String[] args) { | |
Integer[][] testArray = { | |
{ | |
1, 2, 3 | |
}, | |
{ | |
1, 2, 5 | |
}, | |
{ | |
1, 5, 3, 6 | |
} | |
}; | |
for (Integer i : flattenInputArray(testArray)) { | |
System.out.print(i); | |
} | |
} | |
public static Integer[] flattenInputArray(Object[] inputArray) throws IllegalArgumentException { | |
if (inputArray == null) | |
return null; | |
List<Integer> list = new ArrayList<Integer>(); | |
for (Object element : inputArray) { | |
if (element instanceof Integer) { | |
list.add((Integer) element); | |
} | |
else if (element instanceof Object[]) { | |
list.addAll(Arrays.asList(flattenInputArray((Object[]) element))); | |
} | |
else { | |
throw new IllegalArgumentException("InputArray is not valid"); | |
} | |
} | |
return list.toArray(new Integer[list.size()]); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment