[英]Java Collections.binarySearch() returns null
我有一個對象列表和Comparator,用於在該列表中進行排序和搜索。 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調用后,用作鍵的對象臨時值也為null。 我什么都沒學。 我在一個字段中為其他類嘗試了相同的代碼,但效果很好。 任何幫助將不勝感激。
Collections.binarySearch()
的返回類型為int
因此該方法永遠不能返回null
。 它可能返回0
,但這表示該對象在索引0
(即第一個元素)處找到。
而且,在調用Collections.binarySearch()
之后,無法將temp
為null
,因為該方法無法修改temp
的值(因為Java不是通過引用傳遞的)。
當我嘗試在binarySearch
返回后,您的代碼index
為-6
時,表明temp
不在集合中(這是預期的,因為其中沒有indv1
值為25
AttribRow
對象),並將其插入要排序的位置6
。
注意:帶有Indv1 25的AttribRow未添加到列表中,您的代碼缺少rows.add(temp);
在temp.setIndv1((long) 25);
。
另外,我認為重新分配對象temp = new AttribRow()
是容易出錯的做法。
我的代碼也得到-6 ...為什么要使用那么多22 Indv1? 據此,您將懷疑哪個對象是正確的:
使用二進制搜索算法在指定列表中搜索指定對象。 在進行此調用之前,必須根據指定的比較器(如上述的Sort(List,Comparator)方法)將列表按升序排序。 如果未排序,則結果不確定。 如果列表包含等於指定對象的多個元素,則不能保證將找到哪個元素。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.