如果我想调用 binarySearch() 方法来执行搜索操作,是否需要实现比较器或可比较?我在尝试调用 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 方法中作为参数传递什么。
请帮我