【问题标题】:collections.binarySearch() is not working with comparablecollections.binarySearch() 不适用于可比较的
【发布时间】:2013-02-15 00:07:56
【问题描述】:

按升序和降序对列表进行排序后,我想调用 binarySearch 方法。 但它不像我已经实现的那样工作。

 class Student implements Comparable<Student>{
private int id;
private String name;

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

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

@Override
public int compareTo(Student o) {

    int j = o.getId();
    int result = this.id - j;
    return result;
}


}
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("\nSorting in reverse order:");

//  Collections.reverse(list);
    Comparator<Student> collections = Collections.reverseOrder();
    Collections.sort(list, collections);

    Iterator iterator1 = list.iterator();
    while(iterator1.hasNext()){
        Student student = (Student) iterator1.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 at this line.I don't know what to use as argument of                           binarySearch() method. 
}

}

我可以通过实施比较器来做到这一点,但我的项目中有这样的要求 请指导我。

【问题讨论】:

  • 您已删除方法调用的结尾:Collections.binary

标签: comparator comparable


【解决方案1】:

来自 Collections.binarySearch 的文档:

在进行此调用之前,必须根据其元素的自然顺序(如通过 sort(List) 方法)将列表排序为 升序。如果未排序,则结果未定义。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-05
    • 2010-12-27
    • 2021-12-14
    • 1970-01-01
    • 2021-03-08
    • 1970-01-01
    • 2021-05-30
    • 1970-01-01
    相关资源
    最近更新 更多