java中binarysearch方法_Java中Collections的binarySearch方法

48304ba5e6f9fe08f3fa1abda7d326ab.png

public class Student1 implements Comparable {

private String name;

private int age;

public Student1() {

}

public Student1(String name, int age) {

this.name = name;

this.age = age;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public Integer getAge() {

return age;

}

public void setAge(Integer age) {

this.age = age;

}

@Override

public int compareTo(Student1 s) {

int num = this.age - s.age;

int num1 = (num == 0 ? this.name.compareTo(s.name) : num);

return num1;

}

}

调用

import java.util.ArrayList;

import java.util.Collections;

import java.util.List;

import cn.stone.comparable_comparator.Student1;

public class Student1Test {

public static void main(String[] args) {

List list1 = new ArrayList();

list1.add(new Student1("林青霞", 27));

list1.add(new Student1("风清扬", 30));

list1.add(new Student1("刘晓曲", 28));

list1.add(new Student1("武鑫", 29));

list1.add(new Student1("林青霞", 27));

int index=Collections.binarySearch(list1, new Student1("林青霞", 27));

System.out.println(index);

}

}

方法二

public static int binarySearch(List extends T> list, T key, Comparator super T> c)

此方法传入一个列表,要查找的元素,以及一个比较器。

创建对象类

public class Student2 {

private String name;

private int age;

public Student2() {

}

public Student2(String name, int age) {

this.name = name;

this.age = age;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public Integer getAge() {

return age;

}

public void setAge(Integer age) {

this.age = age;

}

}

调用

import java.util.ArrayList;

import java.util.Collections;

import java.util.Comparator;

import java.util.List;

import cn.stone.comparable_comparator.Student2;

public class Student2Test {

public static void main(String[] args) {

List list2 = new ArrayList();

list2.add(new Student2("林青霞", 27));

list2.add(new Student2("风清扬", 30));

list2.add(new Student2("刘晓曲", 28));

list2.add(new Student2("武鑫", 29));

list2.add(new Student2("林青霞", 27));

int index1 = Collections.binarySearch(list2, new Student2("林青霞", 27),

new MyComparator());

System.out.println(index1);

}

}

class MyComparator implements Comparator {

@Override

public int compare(Student2 s1, Student2 s2) {

int num = s1.getAge() - s2.getAge();

int num1 = (num == 0 ? s1.getName().compareTo(s2.getName()) : num);

return num1;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值