一、使用Comparable接口进行排序:如何要都某种数据类型或者是自定义的类进行排序必须要实现Comparable

jdk定义的基本数据类型和String类型的数据都实现了Comparable。下面以实例来展现Comparable的具体实现

1、Comparable接口的定义:

public interface Comparable<T> {
public int compareTo(T o);
}

  Comparable接口只定义了一个方法compareTo(T o);返回int类型的数据。

  该该方法返回3个范围的数据:>0;=0;<0;

  下面是一个实例

public class Grade implements Comparable<Grade> {
private int grade; public Grade(int grade) {
super();
this.grade = grade;
} public int getGrade() {
return grade;
} public void setGrade(int grade) {
this.grade = grade;
} @Override
public int compareTo(Grade grade) { return this.grade - grade.getGrade();
} @Override
public String toString() {
return "Grade [grade=" + grade + "]";
} }

对于字符串进行排序

 public int compareTo(String anotherString) {
int len1 = value.length;
int len2 = anotherString.value.length;
int lim = Math.min(len1, len2);
char v1[] = value;
char v2[] = anotherString.value; int k = 0;
while (k < lim) {
char c1 = v1[k];
char c2 = v2[k];
if (c1 != c2) {
return c1 - c2;
}
k++;
}
return len1 - len2;
}

  

  

05-08 08:34