File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

ClassCastException when converting Object[] to DDog[]

 
Anuradha Prasanna
Ranch Hand
Posts: 115
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

In the above program, i have used Comparator to sort DDog objects by name.
How to convert the Object[] o in line 1 to DDog[] dog?
DDog[] dog = (DDog[]) o; // gives a ClassCastException
 
Henry Wong
author
Marshal
Pie
Posts: 20836
75
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Anuradha Prasanna wrote:In the above program, i have used Comparator to sort DDog objects by name.
How to convert the Object[] o in line 1 to DDog[] dog?
DDog[] dog = (DDog[]) o; // gives a ClassCastException


The toArray() method (that takes no parameters) returns an Object array. Period. It is not an DDog array and hence, can't be casted.

If you want the Set to return a DDog array, use the other toArray() method, the one that has been overloaded to take an array.

Henry
 
Deepak Bala
Bartender
Posts: 6663
5
Firefox Browser Linux MyEclipse IDE
 
Anuradha Prasanna
Ranch Hand
Posts: 115
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


when i use the above lines, to convet TreeSet<DDog> d into DDog[] using the other toArray() method, i get NullPointerException in line 2.
can anyone correct me?
 
Ankit Garg
Sheriff
Posts: 9497
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i get NullPointerException in line 2.

Are you sure?? You'll get a NullPointerException in the loop, as the dArray will contain only 6 elements and the rest of the 14 elements will be null (I'm assuming that you used the same code for creating the TreeSet as in your first code)...
 
Harpreet Singh janda
Ranch Hand
Posts: 317
Eclipse IDE
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You will not get NullPointerException at line 2 because you have added 6 objects to TreeSet and then you are initializing an array of 20 object, so because only first 6 places will be filled with objects and rest will be filled with NULL,

 
Anuradha Prasanna
Ranch Hand
Posts: 115
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks harpreet, i got it now!
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic