Java对象排序
Java对象排序
- import java.util.Arrays;
- import java.util.Comparator;
- public class TestSort {
- public static void main(String[] args) {
- TestSort ts = new TestSort();
- Integer[] it = new Integer[10];
- for (int i = 0; i < 10; i++) {
- it[i] = new Integer(10 - i);
- }
- ts.mergeSort(it, 0, it.length - 1, null);
- System.out.println(Arrays.toString(it));
- // 输出结果为:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
- // 上面是对Integer对象进行排序
- /*************************************************************/
- // 下面是对Person对象进行排序
- PersonCompator pc = new PersonCompator();
- Person[] per = new Person[] { new Person(23, "a"), new Person(12, "b"),
- new Person(1, "c"), new Person(44, "d") };
- ts.mergeSort(per, 0, per.length - 1, pc);
- System.out.println(Arrays.toString(per));
- // 输出结果为:[c:1, b:12, a:23, d:44]
- }
- /*
- * 对于对象比较有两种方法,第一种是重写此类,实现Compareable接口,Integer类就是这么做的,
- * 所以此时可以直接将所有对象自动向上转型为Object,再对其进行比较,进而排序
- *
- * 第二种则是写一个此类的比较类,实现Comparator,下面的Person类就是这么干的,此时只需调用 比较类的compare方法即可
- */
- private <T> void mergeSort(T[] arr, int i, int j, Comparator<? super T> c) {
- if (i < j) {
- int k = (i + j) / 2;
- mergeSort(arr, i, k, c);
- mergeSort(arr, k + 1, j, c);
- merge(arr, i, k, j, c);
- }
- }
- private <T> void merge(T[] arr, int p, int r, int q, Comparator<? super T> c) {
- int n1 = r - p + 1;
- int n2 = q - r;
- T[] L = arr.clone();
- System.arraycopy(arr, p, L, 0, n1);
- T[] R = arr.clone();
- System.arraycopy(arr, r + 1, R, 0, n2);
- int i = 0, j = 0, k = p;
- if (c == null) {
- while (i < n1 && j < n2) {
- if (((Comparable<T>) L[i]).compareTo(R[j]) <= 0) {
- arr[k++] = L[i++];
- } else {
- arr[k++] = R[j++];
- }
- }
- } else {
- while (i < n1 && j < n2) {
- if (c.compare(L[i], R[j]) <= 0) {
- arr[k++] = L[i++];
- } else {
- arr[k++] = R[j++];
- }
- }
- }
- while (i < n1) {
- arr[k++] = L[i++];
- }
- while (j < n2) {
- arr[k++] = R[j++];
- }
- }
- }
- class Person {
- private int age;
- private String name;
- public Person() {
- }
- public Person(int a, String n) {
- this.setAge(a);
- this.setName(n);
- }
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public String toString() {
- return this.getName() + ":" + this.getAge();
- }
- }
- class PersonCompator implements Comparator<Person> {
- public int compare(Person o1, Person o2) {
- return o1.getAge() - o2.getAge();
- }
- }
评论暂时关闭