java - not able to use the comparator in my program -
in program not identifying compartor
, don't want use compareto
.
class testtreeset { public static void main(string args[]) { buildobject build = new buildobject(); treeset treeset = new treeset( new compared()); treeset = build.sendastreeset(); iterator itr = treeset.iterator(); while(itr.hasnext()) { obj object = (obj) itr.next(); system.out.println(object.getname() + "\n " + object.getage() + "\n " + object.getsalary()); } } }
this comparator
class compared implements comparator { public int compare(object , object b) { obj 1 = (obj) a; obj 2 = (obj) b; double salaryone = one.getsalary(); double salarytwo = two.getsalary(); int ageone = one.getage(); int agetwo = two.getage(); if( ageone == agetwo) { if(salaryone > salarytwo) { return -1; } else if(salaryone < salarytwo) { return 1; } else return 0; } else if(ageone > agetwo) return -1; else return 1; } }
what problem ? shows cannot cast java.lang.comparable
exception
since use
treeset treeset = new treeset();
in sendastreeset
method, treeset tries sort elements added using theire natural ordering. witch impiles class of objects musst implement compareable interface.
you should replace line with
treeset treeset = new treeset( new compared());
the same line in main method can removed.
Comments
Post a Comment