DESKTOP-0FT47VC_20200901-罗贤丞

问题

public class DateSort1 {

    public static void main(String[] args) {

        final Random random = new Random();

        final Calendar calendar = Calendar.getInstance();

        final Date[] dates = new Date[5];

        for (int i = 0; i < dates.length; i++) {
            int y = random.nextInt(9999);
            int m = random.nextInt(12);
            int d = random.nextInt(30);
            calendar.set(y, m, d);
            dates[i] = new Date();

            Date date = calendar.getTime();
            dates[i] = date;
        }

        for (int i = 0; i < dates.length; i++) {
            System.out.println("排序前 :" + dates[i]);

        }
        Comparator<Date> comparator = new DateHe();

        Arrays.sort(dates, comparator);

        for (int i = 0; i < dates.length; i++) {
            System.out.println("排序后 :" + dates[i]);
        }
    }

}

解决

public class DateHe implements Comparator<Date> {

    @Override
    public int compare(Date x, Date y) {
        if (x.getTime()<y.getTime()) {
            return -1;
        }else if (x.getTime()==y.getTime()) {
            return 0;
        }else {
            return 1;
        }
        
    }

吐槽

对有些知识理解的还不是很透彻,还需继续努力。

标签

© 2021 成都云创动力科技有限公司 蜀ICP备20006351号-1