Can some one tell me how to add objects to TreeSet?
Do I have to implement comparable in the Dog class to add the Dog object to be added to TreeSet? reason?
I am trying to do that in the above code but getting the compiler error please help..
use Integer size; in line 3 instead of int size; ,as the compareTo() method does not take primitives for comparison.
Comparable interface is implemented, for sorting. As TreeSet is a sorted Set, there is not need to implement Comparable for sorting.
You can add objects to TreeSet as,
as you have done in your code.
You dont have to implement comparable in the Dog class to add the Dog object to be added to TreeSet. Comparable is used for sorting, as in case of TreeSet as it is already Sorted in natural order, no need to implement Comparable for sorting. Comparable is implemented by List & Arrays for sorting. For adding to your TreeSet, just create a TreeSet as in line 1 and add objects to it, as in line2.