【发布时间】:2011-02-23 07:37:11
【问题描述】:
我有一个对象列表和用于在该列表中排序和搜索的比较器。 Collections.binarySearch() 返回 null 而它应该返回一个整数值。这是代码:
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 是映射到表的实体 bean 类。它有一个字段 indv1 用于比较。
private Long indv1;
public Long getIndv1() {
return indv1;
}
public void setIndv1(Long indv1) {
this.indv1 = indv1;
}
这是 Comporator 类的代码
public class CitRowsComparator implements Comparator<AttribRow> {
public CitRowsComparator() {
super();
}
public int compare(AttribRow one, AttribRow two) {
return one.getIndv1().compareTo(two.getIndv1());
}
}
Collections.binarySearch() 总是返回 null。即使我将 Comparator 中的 compare() 方法更改为返回 0,它仍然返回 null。在 binarySearch 调用之后,用作键的对象 temp 也为空。我不参加任何比赛。我为一个字段的其他类尝试了相同的代码,并且效果很好。 任何帮助将不胜感激。
【问题讨论】:
-
binarySearch不返回具有 null 值的类型时,如何返回 null?你怎么知道index是null而不是0? -
这段代码在我的机器上工作,删除
temp.setId((long)55); -
-1 - 这个问题报告了明显不可能的事情。
-
听起来是使用 dbeugger 找出实际问题的好时机。 ;)
标签: java