在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/Java/ 關(guān)于Collections類的binarySearch使用,為什么binaryS

關(guān)于Collections類的binarySearch使用,為什么binarySearch返回值為負(fù)數(shù),還會拋異常,求解

Student.java

private int age;
private String name;

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

public void setAge(int age) {
    this.age = age;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public int getAge() {
    return age;
}

public String toString(){
    return "age:" + age + "\t" + "Name:" + name;
}

Main.java

public class Main {

public static void main(String[] args) {
    Student stu1 = new Student(48, "jre");
    Student stu2 = new Student(25, "JIe");
    Student stu3 = new Student(47, "Lil");
    Student stu4 = new Student(40, "Lilith");
    Student stu5 = new Student(20, "Jack");

    LinkedList linkedList = new LinkedList();
    linkedList.add(stu5);
    linkedList.add(stu4);
    linkedList.add(stu3);
    linkedList.add(stu2);
    linkedList.add(stu1);

    Collections.sort(linkedList, (Student o1, Student o2) ->{
        if (o1.getAge() > o2.getAge()){
            return 1;
        }else if (o1.getAge() == o2.getAge()){
            return 0;
        }else
            return -1;
    });

    int index = Collections.binarySearch(linkedList, stu2);
    System.out.println("二分查找法查找出的Index為:" + index);
    System.out.println("二分查找法查找出的值為:" + linkedList.get(index));

    Iterator it = linkedList.iterator();
    it.forEachRemaining(e -> System.out.println(e));
}

}

回答
編輯回答
夢一場

類轉(zhuǎn)換錯誤?

private static <T>
    int indexedBinarySearch(List<? extends Comparable<? super T>> list, T key) {
        int low = 0;
        int high = list.size()-1;

        while (low <= high) {
            int mid = (low + high) >>> 1;
            Comparable<? super T> midVal = list.get(mid);
            int cmp = midVal.compareTo(key);

            if (cmp < 0)
                low = mid + 1;
            else if (cmp > 0)
                high = mid - 1;
            else
                return mid; // key found
        }
        return -(low + 1);  // key not found
    }

int index = Collections.binarySearch(linkedList, stu2);
Student需要implements Comparable接口

2018年5月5日 19:15