This week's book giveaway is in the Performance forum.
We're giving away four copies of The Java Performance Companion and have Charlie Hunt, Monica Beckwith, Poonam Parhar, & Bengt Rutisson on-line!
See this thread for details.
Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

ClassCastException when converting Object[] to DDog[]

 
Anuradha Prasanna
Ranch Hand
Posts: 115
  • 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: 21212
81
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • 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
  • 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: 9521
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • 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
  • 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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks harpreet, i got it now!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic