| Author |
Assigning double dimension array to single dimension array of type Object
|
ankur trapasiya
Ranch Hand
Joined: Sep 24, 2010
Posts: 160
|
|
public class ID
{
public static void main(String... args)
{
Object [] object = new String[5][5];
int counter=0;
for (Object o : object )
{
counter++;
}
System.out.println(counter);
}
}
this code outputs 5 ...
I am not getting why ...
can anyone explain ??? please ..
|
OCPJP(83%)
|
 |
Kushan Athukorala
Ranch Hand
Joined: Aug 09, 2010
Posts: 33
|
|
Hi Ankur,
Can you tell us what you understand from this code first?
Then we can help you to figure out where you go wrong.
Thanks,
Kushan
|
Kushan Athukorala
OCPJP 6.0 [86%]
|
 |
Mohamed Sanaulla
Bartender
Joined: Sep 08, 2007
Posts: 2926
|
|
Head First Java has beautifully explained this Array concept. I would recommend you to read that book if you have a copy of it. Its worth reading for a beginner.
Also please UseCodeTags to post your source code.
|
Mohamed Sanaulla | My Blog
|
 |
Matthew Brown
Bartender
Joined: Apr 06, 2010
Posts: 3791
|
|
|
Hint: remember that a two-dimensional array is really an array of arrays.
|
 |
ankur trapasiya
Ranch Hand
Joined: Sep 24, 2010
Posts: 160
|
|
hey guys..... my doubt got cleared thankss...
|
 |
Kushan Athukorala
Ranch Hand
Joined: Aug 09, 2010
Posts: 33
|
|
Appreciate your courage
Regards,
Kushan
|
 |
Rahul Saple
Ranch Hand
Joined: Aug 02, 2006
Posts: 46
|
|
Could someone please tell me what exactly is going on behind the scenes. I understand that a two dimensional string array is created and the reference value of that 2-D array is given to a one dimensional Object array reference.
But how is it possible? By that rule the following line of code should compileBut it doesn't. Is it because in Java every Array is an Object? Can anyone shed more light on this?
|
 |
Matthew Brown
Bartender
Joined: Apr 06, 2010
Posts: 3791
|
|
Rahul Saple wrote:Is it because in Java every Array is an Object?
2D array = array of arrays = array of Objects
|
 |
Rahul Saple
Ranch Hand
Joined: Aug 02, 2006
Posts: 46
|
|
I knew I was on to something. So close .Thanks.
|
 |
Ilakya Mukunth
Ranch Hand
Joined: Mar 13, 2012
Posts: 55
|
|
int[][] a = {{1,2},{0,1,2},{-1,0,2}}; // 1
Object[] obj = (Object[])a.clone(); // 2
int [] obj1 = (int[])a.clone(); //3
The line 1 and 2 compiles fine. If I add line-3, it does not run. Can anyone explain me why?
|
 |
 |
|
|
subject: Assigning double dimension array to single dimension array of type Object
|
|
|