繁体   English   中英

我可以在不实现比较器/可比的情况下调用binarySearch方法吗?

[英]Can i invoke binarySearch method without implementing comparator/comparable?

如果我想调用binarySearch()方法来执行Search操作,是否需要实现比较器或可比对象?II在尝试调用binarySearch()方法时面临异常。

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

class Student implements{
private int id;
private String name;

public Student(int id, String name){
    this.id = id;
    this.name = name;
}

public Student() {
    // TODO Auto-generated constructor stub
}

public int getId(){
    return id;
}
public String getName(){
    return name;
}

}
public class CollectionSearchDemo {


public static void main(String[] args) {

    List<Student> list = new ArrayList<Student>();
    list.add(new Student(3, "ouier"));
    list.add(new Student(2, "fdgds"));
    list.add(new Student(7, "kiluf"));
    list.add(new Student(1, "6trfd"));
    list.add(new Student(8, "hjgas"));
    list.add(new Student(5, "ewwew"));

    Collections.sort(list, new Comparator<Student>() {

        @Override
        public int compare(Student arg0, Student arg1) {

            return arg0.getId() - arg1.getId();
        }
    });

    Iterator iterator = list.iterator();
    while(iterator.hasNext()){
        Student student = (Student) iterator.next();
        System.out.print(student.getId()+":"+student.getName()+" ");
    }

    System.out.println("I want to do searching ");
    System.out.println("\n2 is at:"+Collections.binarySearch(list, 2, new Student()));
            // facing exception when i invoke binarySearch method.
}
}

当我尝试搜索“ new Student()”或“ CollectionSearchDemo”作为参数时,发生异常。 我不知道我应该在binraySearch方法中作为参数传递什么。

请帮我

有两种使用Collections.binarySearch 第一个仅包含元素列表和键,但是这些元素必须实现Comparable 第二种方式是带有键和比较器。 如果您不希望Student实现Comparable ,则必须使用此代码。

因此,您必须编写类似:

 Collections.binarySearch(list, studentToBeFound, comparator);

Student studentToBeFoundStudent实例,比较器是Comparator<Student>就像您在Collection.sort()使用的那样。

只需重用您之前与Id比较的Comparator即可:

private static final class StudentComparator implements Comparator<Student> {
  @Override
  public int compare(Student arg0, Student arg1) {

    return arg0.getId() - arg1.getId();
  }
}

然后,如果您要查找ID等于2的学生:

Student studentToBeFound = new Student(2, "dummy string");

并将它们与binarySearch一起使用:

int indexInList = Collections.binarySearch(list, studentToBeFound, new StudentComparator());

binarySearch方法的第三个参数必须是Comparator,因为您的Student类未实现Comparator接口,所以引发了异常。

binarySearch(List list, Object key, Comparator c)

在这里阅读: http : //docs.oracle.com/javase/6/docs/api/java/util/Collections.html

参数c必须是实现Comparator的类的实例。

简短的答案是肯定的-二进制搜索不知道您要搜索的Student是“更大”还是“更小”,而不是列表中的每个学生,因此无法搜索。
您想使用比较器中已有的代码在Student上实现可比性:

public class Student implements Comparable<Student> {
//stuff
 @Override
 public int compareTo(Student o) {
  return getId() - o.getId();
 }
}

然后,您的代码将如下所示:

final Set<Student> set = new TreeSet<Student>();
//add students etc...
final Student found = Collections.binarySearch(set, studentToLookFor);

如果我们不知道如何排序,则无法对列表进行排序。 二进制搜索算法要求对列表进行排序,并使用列表的顺序搜索列表,以便每次迭代将搜索字段切成两半。 但是,关于学生x是在列表的上半部还是列表的后半部的概念要求我们知道此列表的排序方式。

选项1: public class Student implements Comparable<Student>

选项2:为学生编写比较器课程。

public class StudentComparator implements Comparator<Student>

二进制搜索需要一个排序列表。

这种搜索基于分区:

  1. 取中间元素并将其与参考进行比较。
  2. 如果比较表明您的引用为“较低”,则二进制搜索在集合的上半部分继续;如果比较为“较高”,则二进制搜索在下半部分继续。
  3. 当比较返回0 ,找到该元素。

考虑到这一点,实际上是对列表进行排序的要求。 您可以通过不同的方式进行操作:

  • Comparator的帮助下对其进行排序,然后调用binarySerarch
  • 排序实现Comparable接口的元素的集合,然后调用binarySearch
  • 如果提供所需的Comparator则将排序binarySearch方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM