二进制搜索元素字段的对象数组

时间:2014-02-21 21:33:11

标签: java arrays eclipse arraylist binary-search

是否有搜索二进制数组的对象,而不是数组的完整元素,而是包含特定字段值的元素?目前,我看到的唯一方法就是创建一个新的“Entry”对象来搜索 - 而且由于compareTo实现,第二个字段“intial”包含的内容并不重要。

有没有办法实现二进制搜索,这样我就可以直接搜索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
    }
}


}

1 个答案:

答案 0 :(得分:2)

你的问题没有多大意义。

二进制搜索适用于已排序的集合,因此您的元素当然必须具有可比性。定义您的compareToequals方法,仅考虑surname字段,然后您可以使用binarySearch

编辑:我仍然不确定您是否在询问库函数binarySearch 的使用情况,还是关于的实现自定义二进制搜索功能

对于第一种情况,答案是否定的,API中没有binarySearch的这种重载。通常在数组中,您希望按实体相等性进行搜索,因为在此方法的预期用例中,您已经拥有了要搜索的实体,但是您不知道它是否包含在目标数组中,以及在哪个索引上可以被找寻到。但是,您希望通过密钥搜索实体,这可能表示您滥用了ArrayListbinarySearch; SortedMap更适合此任务。

另一方面,如果你坚持使用ArrayList,那么你当然可以自己实现二进制搜索这样的方法,它只使用你的surname字段进行匹配

相关问题