0

For example a 2-D array to a 3-D array.Is it possible using array ? If not, what class should I use to achieve this ?

EDIT : The array dimension is user defined at runtime.

9
  • 5
    Could you give some more details? Commented May 2, 2015 at 16:43
  • 1
    provide some more details with tried code . Commented May 2, 2015 at 16:45
  • The array is declared as a 2-D array and I want to change the array to a 3-D array. Commented May 2, 2015 at 16:47
  • Can you give example of 2-D array and result 3-D array? Commented May 2, 2015 at 16:48
  • The array dimension is user-defined. Commented May 2, 2015 at 16:49

2 Answers 2

2

try this,

 int[][][] convertinto3d(int[][] d2, int size) {
        int[][][] dimention = new int[size][d2.length][d2[0].length];
        for(int a=0; a< size; a++ ) {
        for(int i=0; i<d2.length; i++ ) {

               dimention[a][i] = d2[i]; 

            }


        }

        return dimention;

    }
Sign up to request clarification or add additional context in comments.

Comments

1

You can't change length or dimension of an array, but you can create a new array with different number of dimensions and copy the content of the old array into it.

Small example

    int[] initialArray = new int[]{1,2,3};
    System.out.println(initialArray[0] + " " + initialArray[1] + " "+ initialArray[2]);
    int[][] newArray = new int[initialArray.length][3];
    for (int i=0;i<initialArray.length;i++){
        newArray[i][0] = initialArray[i];
    }
    System.out.println(newArray[0][0] + " " + newArray[1][0] + " "+ newArray[2][0]);

2 Comments

What about using another class like ArrayList ?
The question is what you want to achieve? Is performance important or do you just want to store values?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.