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.
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)...
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,