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;Compilation and execution returns this result:
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) {
TreeSetd = 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());
}
}
Exception in thread "main" java.lang.ClassCastException: TreeSet.Point cannot be cast to java.lang.ComparableThe 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.
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 following code corrects this error by implementing the interface Comparable:
import java.util.Iterator;This program outputs this result:
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) {
TreeSettset = new TreeSet ();
tset.add(new Point(2,4));
tset.add(new Point(1,7));
Point a = new Point(2,5);
Iteratoriterator = tset.iterator();
while(iterator.hasNext()){
Point p = iterator.next();
System.out.print(p.x +", "+ p.y);
System.out.println(" | p > a: "+p.compareTo(a));
}
}
}
2, 4 | p > A: 0References:
1, 7 | p > a: 1
Javadoc: TreeSet class