• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

What is wrong with the following code?

 
suresh sai
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Or because arrays are supposed to be declared the following way ?
Object[] myObject = ...
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Shaveta Chawla
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks shaveta.Thank you very much.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic