-3

I want to create a multidimensional array from existing array:

String arr1[] = new String[]{"1","2","3","4","5","6","7"};

String arr2[] = new String[]{"books","cars","mobile","tickets","flats","toys","chairs"};

String arr3[][] = new String[][]{ arr1, arr2};

The above code creates two rows and seven columns array. But I want to create an array with two columns and seven rows. Can anyone tell me how to create such array?

hsz
  • 148,279
  • 62
  • 259
  • 315

2 Answers2

0

If your third array capacity doesn't change then you use below code snippet

 String arr3[][] = new String[7][2];

      for(int i=0;i<arr1.length;i++){

          arr3[i][0]=arr1[i];
          arr3[i][1]=arr2[i];

          }

arr3:

[[1, books], [2, cars], [3, mobile], [4, tickets], [5, flats], [6, toys], [7, chairs]]
gowtham
  • 977
  • 7
  • 15
  • and what about if the size is not known then how we declare the multidimensional array, Like here we have seven rows but how about making it dynamic to n numbers of rows with fix two columns ? – Himanshu Agarwal Feb 03 '14 at 09:47
  • can do this *String arr3[][] = new String[arr1.length][2];* - Both arr1 and arr2 should be of same length – gowtham Feb 03 '14 at 09:52
0

You can declare your array like this

new String[][] { { "1", "2" }, { "5", "6" }, { "9", "10" } };

or you can use just swap horizontal and vertical indexes to access your array

Bitman
  • 1,996
  • 1
  • 15
  • 18