使用 Collections 实现排序 sort方法 对List 实体类实现Comparable类 示例

package com.test.jj;


import java.util.ArrayList;
import java.util.Collections;

public class Test {
    ArrayList<Test.Men> mens = new ArrayList<Test.Men>();

    public Test() {
        int[] ages = new int[] { 13, 54, 23, 45, 76, 22, 18, 69 };
        for (int i = 0; i < ages.length; i++) {
            mens.add(new Men(ages[i]));
        }
        Collections.sort(this.mens);
    }

    public ArrayList<Test.Men> getMens() {
        return mens;
    }

    public static void main(String[] args) {
        Test test = new Test();
        for (Test.Men men : test.getMens()) {
            System.out.println(men.getAge());
        }
    }
    
    

    public class Men implements Comparable<Men> {
        private int age;

        public Men(int age) {
            super();
            this.age = age;
        }

        public int getAge() {
            return age;
        }

        public int compareTo(Men o) {
            if (age > o.getAge()) {
                return 1;
            } else if (age == o.getAge()) {
                return 0;
            } else {
                return -1;
            }
        }

    }
}

从大到小输出  

 

 

public int compareTo(Men o) {
            if (age > o.getAge()) {
                return 1;
            } else if (age == o.getAge()) {
                return 0;
            } else {
                return -1;
            }
        }

从小到大输出

posted @ 2018-03-16 15:00  晨风啊  阅读(576)  评论(2编辑  收藏  举报