java - Binary search in list with generic elements -


i have list custom elements , need binary search through list. however, getting weird results. guess problem in compareto method, don't know i'm missing.

public static void main(string[] args) {     list<myobject> lista = new arraylist<>();      lista.add(new myobject("myobject 1"));     lista.add(new myobject("myobject 2"));     lista.add(new myobject("myobject 8"));     lista.add(new myobject("myobject 3"));     lista.add(new myobject("myobject 4"));      int = collections.<myobject>binarysearch(lista, new myobject("myobject 2"));     system.out.println(i); //gives weird result if search first 2 elements "myobject 1" or "myobject 2" }   public class myobject implements comparable<myobject> {  private string sadrzaj;  public myobject(string s) {     this.sadrzaj = s; }  //empty constructor, getter, setter...  @override public string tostring() {     return this.sadrzaj; }     @override public int compareto(myobject o) {     if(o.tostring().equals(this.tostring())) {         return 0;     }     return -1; } } 

from reference docs of comparable.compareto(t):

compares object specified object order. returns negative integer, zero, or positive integer object less than, equal to, or greater specified object.

the implementor must ensure sgn(x.compareto(y)) == -sgn(y.compareto(x)) x , y. (this implies x.compareto(y) must throw exception iff y.compareto(x) throws exception.)

the implementor must ensure relation transitive: (x.compareto(y)>0 && y.compareto(z)>0) implies x.compareto(z)>0.

finally, implementor must ensure x.compareto(y)==0 implies sgn(x.compareto(z)) == sgn(y.compareto(z)), z.

it recommended, not strictly required (x.compareto(y)==0) == (x.equals(y)). speaking, class implements comparable interface , violates condition should indicate fact. recommended language

"note: class has natural ordering inconsistent equals."

in foregoing description, notation sgn(expression) designates mathematical signum function, defined return 1 of -1, 0, or 1 according whether value of expression negative, 0 or positive.

where returning positive integer if object greater specified object (myobject)? luiggimendoza ponited out binary search work if items sorted.


Comments

Popular posts from this blog

IF statement in MySQL trigger -

c++ - What does MSC in "// appease MSC" comments mean? -

javascript - Blogger related post gadget image Resize s72-c [ Need Expert Help ] -