Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Arrays and Object

 
Vidhya Ramaswamy
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class Dims{
public static void main(String[] args){
1. int[] []a = {{1,2,},{3,4}};
2. Object o = a;
3. Object o1 = a[0];
4. Object o2 = a[0][0]; // how is this possible when next line is not
5. System.out.println(a[0][0] instanceof Object); /*Compile-error:
Incompatible conditional operand types int and Object*/

6. int[][] a2 = (int[][])o;
7. Integer i2 = a[0][0];
8. Integer[][] a3 = (Integer[][])o; //why ClassCastException

}
}
Could someone please explain why lines 4 and 8 behave in the way they do?
Thanks,
Vidhya
 
Kelvin Chenhao Lim
Ranch Hand
Posts: 513
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Vidhya,

Line 4 compiles because of auto-boxing. The primitive int from the array is automatically wrapped as an Integer object, and this is what gets assigned to the Object reference. This is the same mechanism that allows you to compile statements like "Integer x = 2;".

However, auto-boxing does not occur for instanceof tests. Hence the error for Line 5. Also, auto-boxing only applies to single primitive values, not arrays. Hence the exception on Line 8. (Note that all arrays are themselves objects, even if their elements are primitives).
[ November 18, 2007: Message edited by: Kelvin Lim ]
 
Vidhya Ramaswamy
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, Kelvin.

I get it. Regarding line 8, if the original array that was assigned to the Object was an Integer array, it would have worked as follows:

Integer[][] ii = {{1,2,},{3,4}};
Object oi = ii;
Integer[][] a4 = (Integer[][])oi;

So, this has to do with downcasting. How did I not realise this earlier?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic