Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

compiler error-incompatible types

 
geet kaur
Ranch Hand
Posts: 79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

i am trying to access the elements in the array and if i cats it i mean (int[])o then it gives a classCastException...please help me understnd this

[edit]Disable smilies. CR[/edit]
[ September 14, 2008: Message edited by: Campbell Ritchie ]
 
Campbell Ritchie
Sheriff
Pie
Posts: 49451
64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That is because you can't cast an int to any sort of Object or vice versa. You are declaring o as Object[], so any subclass of Object as an array could be a subclass of that, and therefore an Object[] can be a String[] or Integer[] or AnySortOfClass[]. But it can't be an int[].

The only way you could cast it would be declaring it as Object.Or you could use boxing and use an Integer[] array.

. . . at least I think that's correct.
[ September 14, 2008: Message edited by: Campbell Ritchie ]
 
geet kaur
Ranch Hand
Posts: 79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hey thanks Campbell!!!
got it
 
Campbell Ritchie
Sheriff
Pie
Posts: 49451
64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by geet kaur:
hey thanks Campbell!!!
got it
You're welcome
 
Rob Spoor
Sheriff
Pie
Posts: 20552
57
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Campbell Ritchie:
That is because you can't cast an int to any sort of Object or vice versa.

Actually, with autoboxing you can cast an int to an Integer, and therefore also Object. "Object o = 1;" is quite valid.

You are declaring o as Object[], so any subclass of Object as an array could be a subclass of that, and therefore an Object[] can be a String[] or Integer[] or AnySortOfClass[]. But it can't be an int[].

True, but keep in mind that toArray() will return an Object[]. It is NOT an Integer[], even though the actual contents will be Integers. To do that, you must do the following:


1) you can use any size, like 0. However, toArray on line 2 will create a new array (of the given type! Integer in this case) if the list is larger than the array. Therefore, in this case, toArray will actually return o itself.
 
Campbell Ritchie
Sheriff
Pie
Posts: 49451
64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It took a bit of time to understand Rob's bit about boxing an int to an Object, but he is right; you can actually cast (Object) 1.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic