【问题标题】:Java Collections.binarySearch() returns nullJava Collections.binarySearch() 返回 null
【发布时间】: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


【解决方案1】:

Collections.binarySearch() 的返回类型是int,所以这个方法永远不能返回null。它可能会返回0,但这表明该对象位于索引0(即第一个元素)处。

此外,在您调用 Collections.binarySearch() 之后,temp 不可能是 null,因为该方法无法修改 temp 的值(因为 Java 不是通过引用传递)。

当我在binarySearch 返回后尝试您的代码index-6 时,表明temp 不在集合中(这是预期的,因为没有AttribRow 对象与indv125在那里)并将插入到位置6 进行排序。

【讨论】:

    【解决方案2】:

    你的代码我也得到了-6...为什么你使用这么多 22 Indv1?据此,您将怀疑哪个对象是正确的:

    使用二分搜索算法在指定列表中搜索指定对象。在进行此调用之前,必须根据指定的比较器(如上面的 Sort(List, Comparator) 方法)对列表进行升序排序。如果未排序,则结果未定义。 如果列表包含多个等于指定对象的元素,则无法保证会找到哪一个。

    【讨论】:

      【解决方案3】:

      注意:Indv1 25 的 AttribRow 未添加到列表中,您的代码在 temp.setIndv1((long) 25); 之后缺少 rows.add(temp);

      此外,我认为重新分配对象temp = new AttribRow() 是容易出错的做法。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-09-29
        • 1970-01-01
        • 2015-06-04
        • 2019-08-25
        • 2016-05-28
        • 2016-03-08
        • 2015-12-09
        相关资源
        最近更新 更多