之前Arrays 类中存在sort() 方法, 此方法可以直接对 对象数组进行排序。
1.Comparable接口
可以直接使用java.util.Arrays 类进行数组的排序操作,但对象所在的类必须实现Comparable 接口,用于指定排序接口。
Comparable 接口定义如下:
public interface Comparable<T>{
public int compareTo(T o);
}
此方法返回一个int 类型的数据,但是此int 的值只能是以下三种:
1:表示大于
-1:表示小于
0:表示相等
扫描二维码关注公众号,回复: 1784616 查看本文章定义一个学生类,里面有数字,要求按数字由大到小排序
package demo2; public class Student implements Comparable{ int a; public Student(int a) { super(); this.a = a; } public Student() { super(); // TODO Auto-generated constructor stub } public int compareTo(Object o) { Student t = (Student)o; System.out.println("t.a="+t.a); System.out.println("this.a="+this.a); System.out.println(); if(t.a>this.a) { return 1; }else if(t.a < this.a) { return -1; }else { return 0;} } @Override public String toString() { return "Student [a=" + a + "]"; } }
package demo2; import java.util.Iterator; import java.util.Set; import java.util.TreeSet; public class Test { public static void main(String[] args) { Set set = new TreeSet(); set.add(new Student(6)); set.add(new Student(9)); set.add(new Student(3)); set.add(new Student(4)); set.add(new Student(5)); set.add(new Student(1)); set.add(new Student(8)); set.add(new Student(7)); set.add(new Student(2)); set.add(new Student(10)); Iterator i = set.iterator(); while(i.hasNext()) { Student s = (Student)i.next(); System.out.println(s); } } }
运行结果:
2.分析比较器的排序原理t.a=6 this.a=6 t.a=6 this.a=9 t.a=6 this.a=3 t.a=6 this.a=4 t.a=3 this.a=4 t.a=6 this.a=5 t.a=3 this.a=5 t.a=4 this.a=5 t.a=6 this.a=1 t.a=4 this.a=1 t.a=3 this.a=1 t.a=6 this.a=8 t.a=9 this.a=8 t.a=6 this.a=7 t.a=9 this.a=7 t.a=8 this.a=7 t.a=6 this.a=2 t.a=4 this.a=2 t.a=3 this.a=2 t.a=1 this.a=2 t.a=6 this.a=10 t.a=8 this.a=10 t.a=9 this.a=10 Student [a=10] Student [a=9] Student [a=8] Student [a=7] Student [a=6] Student [a=5] Student [a=4] Student [a=3] Student [a=2] Student [a=1]
实际上比较器的操作,就是经常听到的二叉树的排序算法。通过二叉树进行排序,之后利用中序遍历的方法把内容依次读取出来。
排序的基本原理,使用第一个元素作为根节点,之后如果后面的内容比根节点要大,则放在左子树,如果内容比根节点的内容要大,则放在右子树。
然后以中序遍历(左根右)输出!