Forums Register Login

Another Array question...

+Pie Number of slices to send: Send
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?
+Pie Number of slices to send: Send
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?
+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
In Java there is no concept of 2D arrays. When you say int[][] a, it creates array of arrays.
+Pie Number of slices to send: Send
OK. But what effect is (int[]) providing in the code?
+Pie Number of slices to send: Send
It's unnecessary since a[1] is an int[]
+Pie Number of slices to send: Send
 

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
+Pie Number of slices to send: Send
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.
Legend has it that if you rub the right tiny ad, a genie comes out.
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 665 times.
Similar Threads
doubt in arrays...
get current day of week problem
Doubt in K & B self test
Array initialization
Can you explain this with code...
More...

All times above are in ranch (not your local) time.
The current ranch time is
Apr 16, 2024 03:45:13.