aspose file tools*
The moose likes Beginning Java and the fly likes What is wrong with the following code? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "What is wrong with the following code?" Watch "What is wrong with the following code?" New topic
Author

What is wrong with the following code?

suresh sai
Ranch Hand

Joined: Jul 16, 2007
Posts: 62
hi,
the following code gives ClassCastException.

Object myObjects={new String("foo"),new Boolean(true),new Integer(5)};
Arrays.sort(myobjects);

Is it because of ,myObjects contain different type of objects or it is due to..Object is super class of Arrays.Please tellme ,How can I rectify the error?
Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14687
    
  16

Or because arrays are supposed to be declared the following way ?
Object[] myObject = ...


[My Blog]
All roads lead to JavaRanch
Peter Chase
Ranch Hand

Joined: Oct 30, 2001
Posts: 1970
That code does not compile. If you want help, please PostRealCode.

Assuming that you declare the array properly as Object[], you will then get a ClassCastException.

If you read the API for Arrays.sort(Object[]) you will see there is a specific explanation for why you get that exception.

Finally, you do not need to use new String().
[ August 07, 2007: Message edited by: Peter Chase ]

Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.
Shaveta Chawla
Greenhorn

Joined: Aug 01, 2007
Posts: 13
because Arrays.sort method take a argument which should implement Comparable interface. Your Objects arrays contains different type of objects that are not mutually comparable.

Object[] myObjects={new String("foo"),new String("true"),new String("5")};
Arrays.sort(myObjects);
Object[] myObjects={new Integer("22"),new Integer("10"),new Integer"33")};
Arrays.sort(myObjects);
Object[] myObjects={new Boolean("foo"),new Boolean("true"),new Boolean("5")};
Arrays.sort(myObjects);

would complie and run fine because all three classes implements comparable interface
suresh sai
Ranch Hand

Joined: Jul 16, 2007
Posts: 62
Thanks shaveta.Thank you very much.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: What is wrong with the following code?