有無論如何搜索對象的二進制數組,而不是爲數組的完整元素,而是爲包含特定字段值的元素搜索?目前我看到的唯一方法是創建一個新的「Entry」對象來搜索 - 而且由於compareTo的實現,它並不關心第二個「intial」字段包含的內容。Binary在對象數組中搜索元素的字段
是否有一種實現二分法搜索的方法,以便我可以直接簡單地搜索surname.element字段 - 假定數組已經按姓氏排序了?
我知道我可以迭代搜索每個元素的字段的數組,但在這種情況下,我需要使用binarySearch。
public class Entry implements Comparable<Entry> { //implements allows sorting
public String surname;
public char intial;
public Entry(String surname, String initial, int number) {
this.surname = surname.toUpperCase();
this.intial = initial.toUpperCase().charAt(0); // if whole name entered
//takes first letter only
}
@Override
public int compareTo(Entry o) {
else {
return this.surname.compareTo(o.surname);
}
}
public class EntryList {
public static main(String[] args) {
List<Entry> directory = new ArrayList<Entry>();
directory.add(new Entry("surname", "intial"));
int i = Collections.binarySearch(directory, new Entry("surname", " ")); //doesnt matter whats in intial field
}
}
}
感謝您的評論 - 特別是關於無用的代碼行。重寫一個措辭不良的問題(對此表示歉意) - 假設equals和compareTo方法已被覆蓋,只考慮「surname」字段,是否有實現.binarySearch w/out創建一個新的Entry對象作爲第二個參數的方法? – davidhood2
@ davidhood2編輯我的回答作爲迴應。 – poroszd
@poroszd不是直接實現二分查找,而是實現一個方法,它是標準庫中'binarySearch'的外觀。該方法將使用一個私有構造函數,該對象僅使用比較中使用的字段來初始化對象,然後調用二進制搜索。或者我在這裏錯過了什麼? – Wrap2Win