0

リストを昇順と降順で並べ替えた後、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. 
}

}

コンパレータを実装することでこれを行うこともできましたが、私のプロジェクトにはそのような要件があります。ガイドしてください。

4

1 に答える 1

0

Collections.binarySearch のドキュメントから:

リストは、この呼び出しを行う前に、(sort(List) メソッドによる) 要素の自然な順序に従って昇順に並べ替える必要があります。ソートされていない場合、結果は未定義です。

于 2013-02-15T00:33:18.143 に答える