Example of TreeSet with Comparable in Java

The first example below shows an error made when an object is added to a list of type Set. In a Set, each element must be unique, which is why an object must be compared with the objects in TreeSet before it was inserted.

First, let's take a look at the following code that creates three "Point" objects and adds them to TreeSet.

import java.util.TreeSet; 

class Point {
int x,y;
public Point(int x, int y){
this.x = x;
this.y = y;
}
}

public class ImpComparableWrong {

public static void main(String[] args) {
TreeSet d = new TreeSet();
d.add(new Point(2,4));
d.add(new Point(1,7));
d.add(new Point(5,3));

System.out.println(d.size());
}
}
Compilation and execution returns this result:

Exception in thread "main" java.lang.ClassCastException: TreeSet.Point cannot be cast to java.lang.Comparable
at java.util.TreeMap.compare(Unknown Source)
at java.util.TreeMap.put(Unknown Source)
at java.util.TreeSet.add(Unknown Source)
at TreeSet.Comparable.main(Comparable.java:17)
The reason is that the Point class needs to implement the interface Comparable to allow the TreeSet to hold Point objects. The added object cannot be compared with the elements in TreeSet, the method add() throws an exception ClassCastException. To make an object comparable, you need to implement the Comparable.

The following code corrects this error by implementing the interface Comparable:

import java.util.Iterator; 
import java.util.TreeSet;

class Point implements Comparable{
int x,y;
public Point(int x, int y){
this.x = x;
this.y = y;
}

public int compareTo(Point p) {
double dp2 = (double) Math.sqrt(Math.pow(p.x,2) + Math.pow(p.y,2));
double dp = (double) Math.sqrt(Math.pow(x,2) + Math.pow(y,2));
if(dp > dp2)
return 1;
else
return 0;
}
}

public class Comparabletest {

public static void main(String[] args) {
TreeSet tset = new TreeSet();
tset.add(new Point(2,4));
tset.add(new Point(1,7));

Point a = new Point(2,5);

Iterator iterator = tset.iterator();
while(iterator.hasNext()){
Point p = iterator.next();
System.out.print(p.x +", "+ p.y);
System.out.println(" | p > a: "+p.compareTo(a));
}
}
}
This program outputs this result:

2, 4 | p > A: 0
1, 7 | p > a: 1
References:
Javadoc: TreeSet class