Advertisement
Guest User

Untitled

a guest
Oct 26th, 2016
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.45 KB | None | 0 0
  1. package com.neel.task1;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.Arrays;
  5. import java.util.List;
  6.  
  7. public class FlatIntegerArray {
  8.  
  9. /**
  10. * @param inputArray
  11. * @return
  12. * @throws IllegalArgumentException
  13. */
  14. public static Integer[] flatten(Object[] inputArray) throws IllegalArgumentException {
  15.  
  16. if (inputArray == null)
  17. return null;
  18.  
  19. List<Integer> flatList = new ArrayList<Integer>();
  20.  
  21. for (Object element : inputArray) {
  22. if (element instanceof Integer) {
  23. flatList.add((Integer) element);
  24. } else if (element instanceof Object[]) {
  25. flatList.addAll(Arrays.asList(flatten((Object[]) element)));
  26. } else {
  27. throw new IllegalArgumentException("Input must be an array of Integers or nested arrays of Integers");
  28. }
  29. }
  30. return flatList.toArray(new Integer[flatList.size()]);
  31. }
  32.  
  33. /**
  34. * @param inputArray
  35. * @return
  36. * @throws IllegalArgumentException
  37. */
  38. public static ArrayList<Integer> flattenList(Object[] inputArray) throws IllegalArgumentException {
  39.  
  40. if (inputArray == null)
  41. return null;
  42.  
  43. List<Integer> flatList = new ArrayList<Integer>();
  44.  
  45. for (Object element : inputArray) {
  46. if (element instanceof Integer) {
  47. flatList.add((Integer) element);
  48. } else if (element instanceof Object[]) {
  49. flatList.addAll(Arrays.asList(flatten((Object[]) element)));
  50. } else {
  51. throw new IllegalArgumentException("Input must be an array of Integers or nested arrays of Integers");
  52. }
  53. }
  54. return (ArrayList<Integer>) flatList;
  55. }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement