是否有办法搜索对象的二进制数组,不是搜索数组的完整元素,而是搜索包含特定字段值的元素?目前,我看到的唯一方法是创建一个新的“Entry”对象来搜索 - 并且由于compareTo实现,第二个字段“initial”包含什么并不重要。
有没有一种方法可以实现二分搜索,以便我可以直接搜索 surname.element 字段 - 假设数组已经按姓氏排序?
我知道我可以遍历数组搜索每个元素的字段,但在这种情况下我需要使用二进制搜索。
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
}
}
}
最佳答案
你的问题没有多大意义。
二分搜索适用于排序集合,因此您的元素当然必须具有可比性。定义您的 compareTo
和 equals
方法以仅考虑 surname
字段,然后您可以使用 binarySearch
。
编辑:我仍然不确定您是在询问库函数binarySearch
的用法还是自定义二分搜索函数的实现。
对于第一种情况,答案是否定的,API 中不存在这样的 binarySearch
重载。通常在数组中,您希望通过实体相等性进行搜索,因为在该方法的预期用例中,您已经拥有要搜索的实体,但您不知道它是否包含在目标数组中,以及在哪个索引上可以被找寻到。但是,您想通过键搜索实体,这可能表明您滥用了 ArrayList 和 binarySearch; SortedMap
更适合此任务。
另一方面,如果您坚持使用ArrayList
,那么您当然可以自己实现类似二分搜索的方法,该方法仅使用您的姓氏
匹配字段。
关于java - 对对象数组进行二分查找以查找元素的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21945611/