二分法查找(内含 ? super T的使用分析)

运行时间为对数!

根据年龄查找对应的人,直接上代码,有几种代码,只是在泛型时有些区别,需注意:

代码一:T 使用自己的compareTo

package com.itany.gen.superr;public class Person implements Comparable<Person>{private int age;public Person(int age){this.age=age;}public int getAge(){return age;}public String toString(){return "学生年龄为:"+age;}public int compareTo(Person o){return this.age-o.age;}}package com.itany.gen.superr;public class Test{ private final static int NOT_FOUND=-1; public static void main(String[] args) {Person[] persons={new Person(20),new Person(21),new Person(22),new Person(23),new Person(24)};int findNum=binarySearch(persons,new Person(25));if(findNum==NOT_FOUND)System.out.println("未找到");elseSystem.out.println("找到,"+persons[findNum]); } //二分法对奇偶都可以 此处的?就是T本身 也就是Person类,这是比较正常的一种 public static <T extends Comparable<? super T>> int binarySearch(T[] a,T t) {int low=0;int high=a.length-1;while(low<=high){int mid=low+(high-low)/2;if(a[mid].compareTo(t)>0){high=mid-1;}else if(a[mid].compareTo(t)<0){low=low+1;}elsereturn mid;}return NOT_FOUND; }}

代码二:T使用继承了某父类的compareTo

package com.itany.gen.super2;public class Person implements Comparable<Person>{private int age;public Person(){}public Person(int age){this.age=age;}public int getAge(){return age;}public String toString(){return "学生年龄为:"+age;}public int compareTo(Person o){return this.age-o.age;}}package com.itany.gen.super2;public class Student extends Person{public Student(int age){super(age);}}package com.itany.gen.super2;public class Test{ private final static int NOT_FOUND=-1; public static void main(String[] args) {Student[] students={new Student(20),new Student(21),new Student(22),new Student(23),new Student(24)};int findNum=binarySearch(students,new Student(19));if(findNum==NOT_FOUND)System.out.println("未找到");elseSystem.out.println("找到,"+students[findNum]); }//二分法对奇偶都可以 此处的?就是T是Student类,继承自Person,但Student没有重写Person的compareTo()方法 // 此处的Comparable<? super T>就允许了这种情况,直接使用已经定义的Person implements Comparable<Person>,不需再重写Student自己的compareTo()方法 //继承的Student也是一个Comparable<? super T>,这个写法允许用和父类共有的东西来进行比较(Student也是Person),也不用强制转换 //所以这种泛型的写法允许的可能性多,推荐使用public static <T extends Comparable<? super T>> int binarySearch(T[] a,T t) {int low=0;int high=a.length-1;while(low<=high){int mid=low+(high-low)/2;if(a[mid].compareTo(t)>0){high=mid-1;}else if(a[mid].compareTo(t)<0){low=low+1;}elsereturn mid;}return NOT_FOUND; }}小结:Comparable<? super T>这么写因为T 可能使用自己的compareTo,也有可能使用继承了某父类的compareTo,所以这样写比较规范,完整(因为compareTo是Comparable之下的)。

注意:

还有泛型能继承和覆盖吗?这个问题是想说List<String>继承List<Object>吗?不是,它们没有继承关系。所以List<String>类型的对象不能传给List<Object>类型的参数。你必须把参数类型定义成List<? extends Object>才能接受List<String>类型的对象。参考内容:1 ?url=ZzFE8G2v3L9tL4cr_6R_vZoYhX7U25LeNN-BjxuWKF-GgsIlazzuJ_O3TLfshZS8kf6h32_YBuy3ICneICc-8a2 3

,有理想在的地方,地狱就是天堂

二分法查找(内含 ? super T的使用分析)

相关文章:

你感兴趣的文章:

标签云: