others say that for making a binary search tree with an array of {3,7,1,90,45,67,54,23,...}
it is good to work with TreeSet
.but my code below will throw an exception and I don't know why? my array list"array"
contains 100 objects
that each object开发者_如何学C has two fields 1)digit 2)name
and I want to make a BST
with these objects' digit's field.please help me thanks.
TreeSet<Element> set = null;
set = new TreeSet<Element>();
for(Element e :array){
set.add(e);
}
Iterator it1 = set.iterator();
while (it1.hasNext()) {
Object o1 = it1.next();
System.out.println(o1);
}
Exception:
Exception in thread "main" java.lang.ClassCastException: OBST.Element cannot be cast to java.lang.Comparable
at java.util.TreeMap.put(TreeMap.java:542)
at java.util.TreeSet.add(TreeSet.java:238)
at OBST.GreedyVersion.<init>(GreedyVersion.java:25)
at OBST.GreedyVersion.main(GreedyVersion.java:66)
which is because of line : set.add(e);
This is a really bad question. In your other question (and here), you say that you have an {3,7,1,90,45,67,54,23,...}
. But you're declaring your set TreeSet<Element> set
. So what do you really have? Do you have an array of integers? Or is it an array of Elements
?
If it's really an array of elements, the error message says exactly what the problem is, your Element class must implement Comparable
Your Element
class does not implement the Comparable
interface, which is needed by the TreeSet
.
Implementing the Comparable
interface on Element
will force you to implement the compareTo
method. This will define how objects of type Element
rank against each other. This is needed by the TreeSet
so that it knows how and where to place each Element
in the tree.
Java only supports sortable elements in a TreeSet
. To make an element sortable, it has to implement the Comparable
interface.
I think you're getting that error because the elements you're adding do not implement the Comparable interface. What type of array is it?
精彩评论