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

davidhood2

无论如何,是否要搜索对象的二进制数组,而不是数组的完整元素,而是包含特定字段值的元素?目前,我看到的唯一方法是创建一个新的“ 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
    }
}


}
波罗兹德

您的问题没有多大意义。

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

编辑:我仍然不确定您是否在询问库函数binarySearch用法自定义二进制搜索函数的实现

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

另一方面,如果您坚持使用,那么ArrayList当然可以实现一种类似于二进制搜索的方法,该方法仅使用您的surname字段进行匹配。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章