如何在不使用Java的数组或列表的情况下对整数进行排序?

时间:2014-03-18 03:53:25

标签: java arrays sorting

假设我有一组Employee对象。

单个员工对象具有以下参数:名称,年龄和部门。

我需要按照年龄对Employee对象进行排序。

除了一部分,我知道如何做到这一点。

当我使用compareTo方法时,我需要指定如何对整数进行排序。

如何使它们成为整数或列表数组?

修改

这是我的代码,以进一步阐明我需要做什么。

public class Company {
    public static void main(String [] args){
        Employee[] e = new Employee[13];
        PrimeAgeChecker p = new PrimeAgeChecker();
        Department d = new Department();
        e[0] = new Employee("Counting Guru",55,"Accounting");
        e[1] = new Employee("Counting Pro",45,"Accounting");
        e[2] = new Employee("Counting Savvy",40,"Accounting");
        e[3] = new Employee("Counting Novice",25,"Accounting");
        e[4] = new Employee("Sales Guru",50,"Marketing");
        e[5] = new Employee("Sales Pro",48,"Marketing");
        e[6] = new Employee("Sales Savvy",38,"Marketing");
        e[7] = new Employee("Hiring Guru",58,"Human Resrouces");
        e[8] = new Employee("Hiring Pro",47,"Human Resrouces");
        e[9] = new Employee("Hacking Pro",47,"Information Systems");
        e[10] = new Employee("Hacking Guru",51,"Information Systems");
        e[11] = new Employee("Hacking Savvy",38,"Information Systems");
        e[12] = new Employee("Hacking Novice",23,"Information Systems");


        for(int i = 0;i<e.length;i++){
            System.out.println(e[i] + " " + p.isPrime(e[i]));
        }//end 
    }//end main
}//end company

如您所见,每个Employee对象都有3个参数。

我需要按他们年龄的整数对它们进行排序。

1 个答案:

答案 0 :(得分:8)

您应该查看Arrays

sort方法

public static <T> void sort(T[] a, Comparator<? super T> c)

您需要创建一个Comparator来告诉它如何订购您的员工

http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html

同样,如果您有List或其他类型的Collection,则可以使用Collectionssort方法