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 ?
TreeSet and Comparable
Moderator: admin
-
- Posts: 37
- Joined: Mon Jun 12, 2017 2:16 am
- Contact:
-
- Site Admin
- Posts: 10388
- Joined: Fri Sep 10, 2010 9:26 pm
- Contact:
Re: TreeSet and Comparable
Well, Integer and String classes do implement Comparable. Dok doesn't.
Who is online
Users browsing this forum: No registered users and 41 guests