2011-02-23 71 views
0

我有一个对象和比较器的列表,用于在列表中进行排序和序列化。 Collections.binarySearch()返回null,它应该返回一个整数值。以下是代码:Java 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()alsways返回null。即使当我在Comparator中更改compare()方法返回0时,它仍然返回null。在binarySearch envocation之后,用作键的对象温度也为空。我没有任何预期。我尝试了一个字段的其他类相同的代码,它工作正常。 任何帮助将不胜感激。

+3

哪有'binarySearch'回空当它不返回具有空值的类型?你怎么知道'index'是空的而不是0? – 2011-02-23 07:46:39

+0

此代码在删除'temp.setId((long)55)的机器上工作。 ' – 2011-02-23 07:49:42

+0

-1 - 这个问题是报告公然不可能的事情。 – 2011-02-23 07:59:32

回答

5

返回类型Collections.binarySearch()int所以此方法不能返回null。它可能返回0,但是这将是该对象在索引0(即,第一元件)中发现的指示。

此外,还有没有办法,tempnull您的来电Collections.binarySearch()后,因为该方法不能修改的temp值(如Java不传址引用)。

当我尝试你的代码index-6binarySearch返回,说明temp不在集合中(这是意料之中的,因为没有AttribRow对象与indv1价值25在那里),并将在6位置插入,以排序。

0

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

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

0

I'm越来越-6与您的代码太...为什么你用这么多的22 Indv1?根据这一点,您将怀疑哪个对象是正确的:

使用二进制搜索算法搜索指定对象的指定对象。该列表必须按照指定比较器的升序排序(如上面的Sort(List,Comparator)方法),然后再进行此调用。如果没有排序,结果是不确定的。 如果列表包含与指定对象相同的多个元素,则不能保证会找到哪个元素。