创建一个学生接口,继承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 + " ");
}
}