ONJava.com -- The Independent Source for Enterprise Java
oreilly.comSafari Books Online.Conferences.

advertisement

AddThis Social Bookmark Button
Article:
  Making Java Objects Comparable
Subject:   comparable interface
Date:   2006-08-28 05:08:49
From:   AchalPatel
hi all..
can anybody help in solving problem of sorting using comparable interface.
scenario:
class FedResult
{String title;
String desc;
}
using compareTo method i m sorting Array of FedResult class based on titles and titles are sorted but Desc values are not properly sorted based on titles.
for(int i=0; i nResult[i] = new FedResult();
String temp = sDomain.getResultSetAsHTML(requestUID, viewStyle, i, 1);
nResult[i].setTtl(vRes[i].getTitle());
nResult[i].setDesc(temp);
}
Arrays.sort(nResult);
for(int j=startResult; (j System.out.println("TITLES ARE : "+nResult[j].getTtl() + "\n");
System.out.println("DESC ARE : "+nResult[j].getDesc() + "\n");
}


compareTo method is as follow:
public int compareTo(Object anotherResult)throws ClassCastException{
int retValue = title.compareToIgnoreCase(title2);
if (retValue==0)
return ((String)((FedResult)this).getDesc()).compareToIgnoreCase(((FedResult)anotherResult).getDesc());
else
return retValue;
}


Thanks in advace,
Achal.