我有一个员工的arraylist,我想根据他们的工资对他们进行排序,程序应该从文件中读取每行包含一个员工的一些信息。问题是我应该在对数组进行排序时使用可克隆接口,但它只是不适合我..有人可以帮忙吗?
按照排序方法:
public static ArrayList<Worker> sort(ArrayList<Worker> _workers) throws CloneNotSupportedException{
Worker temp;
for (int i=0;i<_workers.size();i++){
if ((_workers.get(i)).compareTo(_workers.get(i+1))==1){
temp=(Worker) _workers.get(i).clone();
_workers.set(i, _workers.get(i+1));
_workers.set(i+1, temp);
}
}
return _workers;
}
遵循克隆方法(我在每个子类中重复它):
public SalariedEmployee clone() throws CloneNotSupportedException{
SalariedEmployee objClone=new SalariedEmployee();
objClone.setIdNumber(this.getIdNumber());
objClone.setName(this.getName());
objClone.setHours(this.getHours());
objClone.setHourRate(this.getHourRate());
return objClone;
}
答案 0 :(得分:0)
在您的worker类中,实现Comparable接口,如:
public class Worker implements Cloneable, Comparable<Worker> {
....
public int compareTo(Worker worker) {
return Double.compare(this.salary, worker.getSalary());
}
}
然后假设你已经有工人名单,你可以这样说:
Collections.sort(listOfWorkers);
clone与排序集合或数组无关,但可以实现多个接口。