如何在Java中按升序排序数组中的对象?

时间:2014-03-17 23:41:57

标签: java arrays sorting

我之前曾有点问过这个问题,但还不够清楚。

我需要通过在Department Class中创建方法来按年龄对Employee对象进行排序。 我已经搜索过,但我似乎无法解决这个问题,因为我感到非常沮丧,所以任何帮助都会很棒。 公司类也是我的主要方法。这里主要关注的是比较员工对象的年龄,然后如果员工只在部门信息系统或会计中进行排序。

我知道Comparable和Comparator,但是即使在研究之后也不知道如何正确实现它们。

感谢。

CODE

员工类:

public class Employee implements Comparable {

private String name;
private int age;
private String department;

public String getDept(){
    return department;
}//end dept

public void setDept(String dept){
    this.department = dept;
}//end

public String getName(){
    return name;
}//end name

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

public int getAge(){
    return age;
}//end age

public void setAge(int a){
    this.age = a;
}//end




public Employee (String n,int age,String dept){

    this.name = n;
    this.age = age;
    this.department = dept;

}//end employee
}//end class

系类:

public class Department   {




}//end department

公司类:

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

2 个答案:

答案 0 :(得分:0)

Comparable和Comparator提供2种不同的排序机制。可比较对于具有自然排序的Objetcs非常有用,例如单词或数字。对于Employee对象,这可能是员工ID。

Comparator提供了一种基于某种任意方法对Objetcs进行排序的机制,并允许根据需要以多种不同方式对对象进行排序。

java.util.Collectionsjava.util.Arrays都提供了使用Comparable对象和使用Comparators进行排序的方法。

您的问题是基于排序整数,它具有自然顺序。请查看java.lang.Integer

的文档

答案 1 :(得分:0)

你必须熟悉可以传递比较器的Arrays.Sort(...)

Comparator

MyComparator implements Comparator<Employee>.... and implement your logic

第二,您需要对数组进行排序:

Arrays.sort(e,new MyComparator());