二面的排序问题(第一版)

发布于 2021-08-10  49 次阅读


package com.apesblog.finedo;

public class People implements Comparable {
    private String name;
    private String date;

    public People(String name, String date) {
        this.name = name;
        this.date = date;
    }

    public People() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    @Override
    public int compareTo(Object o) {
        People p = (People) o;
        if (date.compareTo(p.date) > 0) {
            return 1;
        } else if (date.compareTo(p.date) < 0) {
            return -1;
        } else {
            if (name.compareTo(name) > 0) {
                return 1;
            } else if (name.compareTo(p.name) < 0) {
                return -1;
            }
            return 0;
        }
    }

    @Override
    public String toString() {
        return "People [name=" + name + ", date=" + date + "]";
    }

}
package com.apesblog.day_22;

import java.util.Arrays;

public class Test1 {

    public static void main(String[] args) {
        People[] p = new People[4];
        p[0] = new People("c", "1998");
        p[1] = new People("b", "1997");
        p[2] = new People("d", "1998");
        p[3] = new People("a", "1997");
        mysort(p);
//        Arrays.sort(p);
        System.out.println(Arrays.toString(p));
    }

    public static void mysort(People[] p) {
        for (int i = 0; i < p.length - 1; i++) {
            for (int j = p.length - 1; j > i; j--) {
                if (p[j].getDate().compareTo(p[i].getDate()) < 0) {
                    People t = p[j];
                    p[j] = p[i];
                    p[i] = t;
                } else if (p[j].getDate().compareTo(p[i].getDate()) == 0) {
                    if (p[j].getName().compareTo(p[i].getName()) < 0) {
                        People t = p[j];
                        p[j] = p[i];
                        p[i] = t;
                    }
                }
            }
        }
    }

}