I have a list of objects and Comparator which is used for sorting and serching in that list. Collections.binarySearch() return null while it supposed to return an integer value. Here is the code :
List<AttribRow> rows = new ArrayList<AttribRow> ();
AttribRow temp = new AttribRow();
temp.setIndv1((long)22);
rows.add(temp);
temp = new AttribRow();
temp.setIndv1((long)22);
rows.add(temp);
temp = new AttribRow();
temp.setIndv1((long)22);
rows.add(temp);
temp = new AttribRow();
temp.setIndv1((long)23);
rows.add(temp);
temp = new AttribRow();
temp.setIndv1((long)22);
rows.add(temp);
temp = new AttribRow();
temp.setIndv1((long)25);
temp.setId((long)55);
Collections.sort(rows, new CitRowsComparator());
int index = 0;
index = Collections.binarySearch(rows, temp,new CitRowsComparator());
AttribRow is entity bean class mapped to the table. It has a field indv1 which is used in comparison.
private Long indv1;
public Long getIndv1() {
return indv1;
}
public void setIndv1(Long indv1) {
this.indv1 = indv1;
}
This is a code for Comporator class
public class CitRowsComparator implements Comparator<AttribRow> {
public CitRowsComparator() {
super();
}
public int compare(AttribRow one, AttribRow two) {
return one.getIndv1().compareTo(two.getIndv1());
}
}
Collections.binarySearch() alsways returns null. Even when I changed compare() method in Comparator to return 0 it was still returning null. Object temp thaht used as a key is also null after binarySearch envocation. I don’t ge any expetions. I tried the same code for other class with one field and it worked fine.
Any help will be appreciated.
The return type of
Collections.binarySearch()isintso this method can’t ever returnnull. It might return0, but that would be an indication that the object is found at index0(i.e. the first element).Also, there’s no way that
tempisnullafter your call toCollections.binarySearch()since that method can’t modify the value oftemp(as Java is not pass-by-reference).When I try your code
indexis-6afterbinarySearchreturns, indicating thattempis not in the collection (which is expected, as noAttribRowobject withindv1value25is in there) and would be inserted at position6to be sorted.