数据结构之选择查找(泛型改造一)

创建一个学生接口,继承comparable

实现一个comparableTo()的方法

//注意这里的Comparable<>的类型是一个学生生类
public class Student implements Comparable<Student> {

    private String name;
    private int score;

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

    @Override
    public String toString() {
        return String.format("Student(name: %s,score: %d)", name, score);
    }

    //equals是Object父类的一个函数,这里是覆盖是equals的方法,因此传进去的也应该是Object
    public boolean equals(Object student){

        if(this == student)
            return true;
        if(this == null)
            return false;
        if (this.getClass() != student.getClass() )
            return false;
        else {
            Student student1 = (Student) student;
            //忽略大小写,也可查找
            return this.name.toLowerCase().equals(student1.name.toLowerCase());
        }
    }

    public int compareTo(Student student){
        return this.score - student.score;
    }

}

实例化泛型选择排序

public class SelectionSort {
    private SelectionSort() {
    }

    ;

    //泛型方法,必须可比较的
    public static <E extends Comparable<E>> void sort(E[] arr) {
        for (int i = 0; i < arr.length; i++) {
            int minIndex = i;
            //查找数组里面最小的那个数,进行无序查找
            for (int j = i; j < arr.length; j++) {
                if (arr[j].compareTo(arr[minIndex]) < 0) {
                    minIndex = j;
                }
            }
            swap(arr, i, minIndex);
            //进行数据对换,进行有序

        }
    }

    private static <E> void swap(E[] arr, int i, int j) {
        E t = arr[i];
        arr[i] = arr[j];
        arr[j] = t;
    }

    public static void main(String[] args) {
        //接收的是泛型,这里的arr类型要改成Integer
      /*  Integer[] arr = {5, 1, 6, 3, 4, 2, 7};
        SelectionSort.sort(arr);
        for (int i = 0; i < arr.length; i++) {
            if(i==0){
                System.out.print("[");
            }if(i < 6)
                System.out.print(arr[i] + ",");
            else {
                System.out.println(arr[i] + "]");
            }
        }*/
        Student[] students = {new Student("lili", 100),
                new Student("xiaoxiao", 98),
                new Student("jilinggou", 55)};
        SelectionSort.sort(students);
        for(Student student: students)
            System.out.println(student + " ");
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值