Search code examples
javaarraysobjectexpand

Expanding Object array to an object 2d array


I am stuck on a problem which requires me to expand an Object array into a 2D Object array. This is the default code they gave me. Does anyone have any clue?

 Object[][] expand(Object[] array){

 }

The question itself says:

Write a function that takes in an Object[] array, where each value in array is itself an Object[] and returns an Object[][] with the same value as the input.

Hint: You will need to do some typecasting/type conversion. You can do this in one single line.


Solution

  • The Question seems to be clear. You are given a 2d array already but just that the inner array is given in the form of Object class object. Because Object is is parent class for all the classes (even the array is a class internally). You just need to typecast and return the 2d array.

    Object[][] expand(Object[] array){
          Object[][] result = new Object[array.length][];
          for(int i=0;i<array.length;i++){
              result[i] = (Object[])array[i];
          }
          return result;
        }