今天学到这个知识点,在使用Array.sort(Object[])
可以对任意类型的数组进行排序,但是这涉及到了泛型的知识,要实现对任意类型数组排序,需要实现Comparable<T>
这个接口:
public interface Comparable<T> {
public int compareTo(T o); //参数为泛型T
/**
* 返回负数: 当前实例比参数 o 小
* 返回0: 当前实例与参数 o 相等
* 返回正数: 当前实例比参数 o 大
*/
}
设计一个程序,实现对名字或年纪的排序。
/**
* 按名字字母排序
*/
public class test {
public static void main(String[] args) {
Person[] person = new Person[] {
new Person("Anna", 12),
new Person("Tina", 31),
new Person("Jack", 25),
};
Arrays.sort(person);
System.out.println(Arrays.toString(person));
}
}
class Person implements Comparable<Person> {
String name;
int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
public int compareTo(Person other) {
return this.name.compareTo(other.name);
}
public String toString() {
return this.name + ", " + this.age;
}
}
运行结果为:
[Anna, 12, Jack, 25, Tina, 31]
结果可见,确实排了序。来剖析一下这个案例。
先new
了三个Person对象,然后将这三个对象传值给Array.sort
进行排序,因为Person对象里包含了String
和int
类型,用泛型的话,就要实现Comparable<Person>
。
当程序执行到Arrays.sort(person);
时,下一步,程序会转到Person
类入口,紧接着下一步就来到了public int compareTo(Person other)
这个方法,这里的(Person other)
参数,传入的是person[0]
元素,类Person
的构造函数传入的是person[1]
元素。这样,就可以参加比较了。
下面看这句:
//this.name 即 person[1] 元素
//other.name 即 person[0] 元素
compareTo(String anotherString)
:按字典顺序比较两个字符串,比较是基于字符串中每个字符的Unicode值。
- 如果返回的值大于0,则说明
this.name
的值比 other.name
的值小
- 如果返回的值等于0,则说明
this.name
的值比 other.name
的值相等
- 如果返回的值小于0,则说明
this.name
的值比 other.name
的值大
注意,不要想当然的以为大于0就是1,小于0就是-1。
同样的,如果按年纪进行排序的话,可以这样:
public int compareTo(Person other) {
/**
* 按名字字母排序
* return this.name.compareTo(other.name);
*/
return (Integer.valueOf(this.age)).compareTo(Integer.valueOf(other.age));
/**
* 按年纪大小排序
* return (Integer.valueOf(this.age)).compareTo(Integer.valueOf(other.age));
*/
}
运行结果为:
[Anna, 12, Jack, 25, Tina, 31]
若要按年纪从大到小排序,只需调整 person[i]
与 person[i+1]
的顺序即可。
另一个是假如年纪相等,则按姓名排序:
public int compareTo(Person other) {
int age = this.age - other.age;
if (age == 0) { age = this.name.compareTo(other.name); }
return age;
}