On Oct 29, 9:24 am, Caleb Josue Ruiz Torres <[email protected]> wrote:
> Hello there all!
> i'm working with the lab-1008 of collection framework... and doing the
> homework of the TreeSet Class i get this exception
> ---------------Exception------------
> run:
> Exception in thread "main" java.lang.ClassCastException: homework.MyOwnClass
> cannot be cast to java.lang.Comparable
> at java.util.TreeMap.put(TreeMap.java:542)
> at java.util.TreeSet.add(TreeSet.java:238)
> at homework.MyTreeSet.main(MyTreeSet.java:18)
> Java Result: 1
> BUILD SUCCESSFUL (total time: 2 seconds)
> ---------------------------------------
>
> Can Anybody Help Me?
> here is the code
>
> ----------------------code-------------
> package homework;
> import java.util.Iterator;
> import java.util.TreeSet;
> public class MyTreeSet {
> public MyTreeSet(){}
> public static void main(String[] args) {
> TreeSet ts = new TreeSet();
I believe, the problem lies in the disparate objects being added into
the treeset. One way to overcome this is to supply a comparator when
creating the treeset. For example:
TreeSet ts = new TreeSet(orderbyString);
Comparator orderbyString=new Comparator(){
int compare(Object o1, Object o2){
return o1.toString().compareTo(o2.toString());
}
};
> MyOwnClass obj1 = new MyOwnClass();
> MyOwnClass obj2 = new MyOwnClass();
> ts.add("uno");
> ts.add("dos");
> ts.add(obj1);
> ts.add(obj2);
> ts.add(new Integer(3));
> ts.add(new Integer(2));
> ts.add(new Integer(1));
> Iterator it = ts.iterator();
> while(it.hasNext()){
> System.out.println("Iterator->" + it.next());
> }
> }//void main}//end of class
>
> ------------------------------------
>
> thanks in advance
--~--~---------~--~----~------------~-------~--~----~
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/javaprogrammingwithpassion?hl=en
-~----------~----~----~----~------~----~------~--~---