• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Why does this work?

 
Ranch Hand
Posts: 71
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
public static void main(String [] args) {

int[][] a = {{1,2},{0,1,2},{-1,0,2}}; // 1
Object[] obj = (Object[])a.clone(); // 2
for(int i = 0; i < obj.length; i++) { // 3
int[] ia = (int[])obj[i]; // 4
System.out.print(ia[i]); // 5
}

On line // 2 how is it possible to clone a two dimensional array and cast it into a 1 dimensional array? I really don't understand what is going on here. It would make sense conceptually if it said: Object[][] obj = (Object[][])a.clone(); but that isn't the case.

Could someone shed some light?
[ February 06, 2006: Message edited by: Arthur Blair ]
 
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Consider that in Java...
  • Multi-dimensional arrays are really just arrays of arrays.
  • Arrays are objects.
  • So if we have int[][] a, the array "a" is really just a single-dimension array of Objects. In particular, these Objects are int arrays.
    [ February 06, 2006: Message edited by: marc weber ]
     
    Ranch Hand
    Posts: 91
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    it is still nt clear. could you please explain more with Eg.
    Is there any good doc on cloning in 2-d array.

    Please help
     
    Ranch Hand
    Posts: 2412
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Consider the first line of code.



    Here what is being created is an array.

    This array contains three elements, the first is an int array with 2 ints, the second is an int array with 3 ints, and the third is an int array with 3 ints.

    As Mark said, there is no direct support for multidimensional arrays in Java. We build them as arrays of arrays.
     
    reply
      Bookmark Topic Watch Topic
    • New Topic