permaculture playing cards*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Another Array question... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Another Array question..." Watch "Another Array question..." New topic
Author

Another Array question...

Higgledy Smith
Ranch Hand

Joined: Mar 07, 2006
Posts: 192
Given:
int [][] a = {{1,2,}, {3,4}};
int[] b = (int[]) a[1];

This (int[]) in the above code is casting a 2-D array to a 1-D array?
Higgledy Smith
Ranch Hand

Joined: Mar 07, 2006
Posts: 192
int [][] a = {{1,2,}, {3,4}};
int[] b = (int[]) a[1];
Object o1 = a;

I don't understand why I can set my instance ref o1 to the instance ref of array a? I thought that the object o1 would have had to been a 2-D?

Is it possible to display the contents of o1? As it is written now?
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
In the original question, a[1] is an array of ints, so the cast is legal.

Recall that arrays are objects, and you can refer to any array as an Object.
Kj Reddy
Ranch Hand

Joined: Sep 20, 2003
Posts: 1704
In Java there is no concept of 2D arrays. When you say int[][] a, it creates array of arrays.
Higgledy Smith
Ranch Hand

Joined: Mar 07, 2006
Posts: 192
OK. But what effect is (int[]) providing in the code?
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
It's unnecessary since a[1] is an int[]
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18748
    
  40

Originally posted by Higgledy Smith:
OK. But what effect is (int[]) providing in the code?


In the example, a[1] is already an int array, so the cast is not needed.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Higgledy Smith
Ranch Hand

Joined: Mar 07, 2006
Posts: 192
OK. I guess the example is not a good one. I was more trying to get someone with experience to tell me it is really casting an array. This is NOT explained in the SCJP 5.0 book but shows up in the self test on page 267.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Another Array question...