• Post Reply Bookmark Topic Watch Topic
  • New Topic

I got a question about [ ] [ ] [ ].  RSS feed

 
Waez Ali
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
HI,
If it allows [3][3] = [2][1]
then why it doesn't print ...
Plese check out this code.

class A13{}
public static void main (String[] args) {
A13[] a1 = new A13[1]; // 1
A13[][] a2 = new A13[2][1]; // 2
A13[][][] a3 = new A13[3][3][3]; // 3
a1[0] = new A13(); // 4
a2[0] = a2[1] = a1; // 5
a3[0] = a3[1] = a3[2] = a2; // 6
System.out.print(a3[2][0][0]); // 7
// System.out.print(a3[2][2][2]); // 8 Array index exception
}
output
------------
A13@1ea2
Why it doesn't print NULL at line 7 ?
Please explain it.

Thanks
 
Jeroen Wenting
Ranch Hand
Posts: 5093
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
a3[2] is a2, which is an array.
Thus a3[2][2] == a2[2]
a2[2] is a1, which is an array.
Thus a2[2][2] == a1[2]
a1 only has 1 element so a1[2] doesn't exist.
 
Roy Tock
Ranch Hand
Posts: 83
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First, note that

a3[2] = a2
a3[2][0] = (a3[2])[0] = a2[0] = a1
a3[2][0][0] = (a3[2][0])[0] = a1[0], which is the A13 created in line 4.

A13's toString() is just Object.toString, which is the class name followed by @ followed by the object's hash code, all of which is not null.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!