Page 1 of 1

TreeSet and Comparable

Posted: Mon Nov 06, 2017 10:34 am
by horst1a
Hello,
the question is about TreeSet and Comparable interface.
I ve always thought when using TreeSet and its add-methods I should always implement Comparable - Interface and implement compareTo-method.
But when i type TreeSet to Integer or String, this seems not to be necessary.
Here is the code:

public class Dok {
int size;
Dok(int s){size = s;}
public static void main(String args[]){

TreeSet<Integer> i = new TreeSet<Integer>();
TreeSet<String> s = new TreeSet<String>();
TreeSet<Dok> dog = new TreeSet<Dok>();
i.add(1); i.add(2);i.add(1);
System.out.println(i);
//dog.add(new Dok(1)); dog.add(new Dok(2));dog.add(new Dok(1));
System.out.println(dog);
s.add("1"); s.add("2");s.add("1");
System.out.println(s);
}

Compiles and runs fine. Only when I want to add objects of class Dok i get the exception.
Where is the difference ?

Re: TreeSet and Comparable

Posted: Mon Nov 06, 2017 9:28 pm
by admin
Well, Integer and String classes do implement Comparable. Dok doesn't.