在排序任务中,可将其分为自然排序:数值大小、字符Asics码序列的排序;客户化排序:也即通过自定义的序列方式进行排序。
1. 自然排序
在JDK类库中,有一部分类实现了Comparable接口,如Integer Double和String等,如下Integer类实现了Comparable的接口,通过重写compareTo方法定义了排序的规则:
返回值 | 含义 |
---|---|
-1 | 大于 |
0 | 等于 |
1 | 小于 |
//Integer类中部分源码;实现了Comparable的接口,可以进行自然排序
public final class Integer extends Number implements Comparable<Integer> {
public int compareTo(Integer anotherInteger) {
return compare(this.value, anotherInteger.value);
}
public static int compare(int x, int y) {
return (x < y) ? -1 : ((x == y) ? 0 : 1);
}
}
JDK中实现了Comparable接口的类库
类名 | 排序方式 |
---|---|
BigDecimal BigInteger Byte Double Float Integer Long Short | 按数字大小排序 |
Character | 按字符的Unicode值的数字大小排序 |
String | 按字符中字符的Unicode值排序 |
注意:使用自然排序时只能向集合中加入同类型的对象,并且这些对象的类必须实现Comparable接口 。
2. 客户化排序
2.1使用Comparable接口
对自己定义的类,设置规则实现排序。如:对学生信息先按照学号升序,再按照成绩降序排列;
创建学生类:
public class A04_Comparable_Student implements Comparable<A04_Comparable_Student> {
private String name;
private int id;
private float score;
public A04_Comparable_Student(String name, int id, float score) {
// TODO Auto-generated constructor stub
this.name = name;
this.id = id;
this.score = score;
}
/**
* @return the id
*/
public int getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(int id) {
this.id = id;
}
/**
* @return the name
*/
public String getName(