java...based on Collections -


import java.util.arraylist; import java.util.*;  class employee1 implements comparable<employee1> {     int empno;      string name;     employee1(int i,string j) {         empno=i;         name=j;     }      public int compareto(employee1 e1) {         employee1 e2=this;         integer i1=e1.empno;         integer i2=e2.empno;         return i1.compareto(i2);     } }  public class employee {     public static void display(arraylist<employee1> i) {         for(employee1 o:i){             system.out.println(o.empno);         }     }      public static void main(string[] args) {         arraylist<employee1> ob=new arraylist<employee1>();         employee1 e1=new employee1(1001,"a");         employee1 e2=new employee1(1002,"b");         ob.add(e2);         ob.add(e1);         collections.sort(ob);         display(ob);     } } 

the output should 1001 1002 instead output 1002 1001.

first passed e2 object empno list , e1 empno of 1001

due compareto method in employee1 - e1.compareto(e2); should same 1001.compareto(1002); why showing in wrong order?

change

  return i1.compareto(i2); 

to

  return -i1.compareto(i2); 

or

  return i2.compareto(i1); 

Comments

Popular posts from this blog

Delphi XE2 Indy10 udp client-server interchange using SendBuffer-ReceiveBuffer -

Qt ActiveX WMI QAxBase::dynamicCallHelper: ItemIndex(int): No such property in -

Enable autocomplete or intellisense in Atom editor for PHP -