TreeSet and Comparable

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
horst1a
Posts: 37
Joined: Mon Jun 12, 2017 2:16 am
Contact:

TreeSet and Comparable

Post 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 ?

admin
Site Admin
Posts: 10388
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: TreeSet and Comparable

Post by admin »

Well, Integer and String classes do implement Comparable. Dok doesn't.

Post Reply

Who is online

Users browsing this forum: No registered users and 41 guests