Skip to content

Instantly share code, notes, and snippets.

@smhjamalii
Last active January 3, 2019 20:22
Show Gist options
  • Save smhjamalii/4cafb3403aced707dc846fa9b39c0fbb to your computer and use it in GitHub Desktop.
Save smhjamalii/4cafb3403aced707dc846fa9b39c0fbb to your computer and use it in GitHub Desktop.
ArrayUtils.java
public class ArrayUtils {
public static Object[] flatten(Object[] array){
Object[] flattenedArray = new Object[0];
for(int i = 0; i < array.length; i++){
if(array[i] instanceof Object[]){
flattenedArray = addAll(flattenedArray, flatten((Object[]) array[i]));
} else {
flattenedArray = add(flattenedArray, array[i]);
}
}
return flattenedArray;
}
private static Object[] add(Object[] array, Object object){
Object[] newArray = new Object[array.length + 1];
for(int i = 0; i < array.length; i++){
newArray[i] = array[i];
}
newArray[newArray.length - 1] = object;
return newArray;
}
private static Object[] addAll(Object[] array, Object[] objects){
Object[] newArray = new Object[array.length + objects.length];
for (int i = 0; i < array.length; i++) {
newArray[i] = array[i];
}
for (int i = array.length; i < newArray.length; i++) {
newArray[i] = objects[i - array.length];
}
return newArray;
}
public static Object[] populateSampleArray(){
// Creating a nested array of objects
Object[] array = new Object[2];
array[0] = new Object[3];
((Object[]) array[0])[2] = new Object[1];
// Initialize array indices
array[1] = 4;
((Object[]) array[0])[0] = 1;
((Object[]) array[0])[1] = 2;
((Object[]) ((Object[]) array[0])[2])[0] = 3;
return array;
}
}
import java.io.IOException;
/**
*
* @author Seyed Mohammad Hossein Jamali (smhjamali@yahoo.com)
*/
public class ArrayUtilsTest {
public static void main(String[] args) throws IOException {
// Populate a sample array
Object[] array = ArrayUtils.populateSampleArray();
// Call flattenArray
Object[] result = ArrayUtils.flatten(array);
// Print contents of final array
for (int i = 0; i < result.length; i++) {
System.out.print(result[i] + ",");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment