账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    关于Collections类的binarySearch使用,为什么binarySearch返回值为负数,还会抛异常,求解
    86
    0

    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));
    }

    }

    0
    打赏
    收藏
    点击回答
        全部回答
    • 0
    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部