aspose file tools*
The moose likes Beginning Java and the fly likes compiler error-incompatible types Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "compiler error-incompatible types" Watch "compiler error-incompatible types" New topic
Author

compiler error-incompatible types

geet kaur
Ranch Hand

Joined: Sep 03, 2008
Posts: 78

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

Joined: Oct 13, 2005
Posts: 40052
    
  28
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

Joined: Sep 03, 2008
Posts: 78
hey thanks Campbell!!!
got it
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 40052
    
  28
Originally posted by geet kaur:
hey thanks Campbell!!!
got it
You're welcome
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19785
    
  20

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.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 40052
    
  28
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: compiler error-incompatible types