将对象添加到arraylist并对其进行排序

时间:2013-06-05 05:29:10

标签: java arrays sorting

我编写了一个程序,在其中我将对象添加到arraylist,然后按ID对其进行排序。这是我的计划:

package TestPackage;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;

import com.fulcrum.emp.EmployeeSortById;

public class EmployeeSorting {
    // path till 'employee files' folder.
    File folder = new File("D:\\Arthi iyer\\employee files");

    // listFiles() : list all the files in a folder.
    File[] listOfFiles = folder.listFiles();

    ArrayList<Employee> emp = new ArrayList<Employee>();
    String[] split_input = null;

    public void sortFiles() throws FileNotFoundException {

        for (File file : listOfFiles) {
            Scanner scanner = new Scanner(file);
            String input = scanner.nextLine();
            split_input = input.split("=");
            int id = Integer.parseInt(split_input[1]);

            String input1 = scanner.nextLine();
            split_input = input1.split("=");
            String name = split_input[1];

            String input2 = scanner.nextLine();
            split_input = input2.split("=");
            int age = Integer.parseInt(split_input[1]);

            // Employee e=new Employee(id, name, age);
            // System.out.println(e);
            emp.add(new Employee(id, name, age));
            // System.out.println(emp.size());

            // for(int i=0;i<emp.size();i++)
            // {
            // System.out.println(emp.get(i) +""+i);
            // }

        }// for ends
    }// method ends

    public void sortByID() {

        System.out.println("----Sort By Employee Id----");
        Collections.sort(emp, new EmployeeSortById());
    }

    public static void main(String[] args) throws FileNotFoundException {

        EmployeeSorting sort = new EmployeeSorting();
        sort.sortFiles();
        sort.sortByID();

    }

}

我的问题是它出错了:

  

类型集合中的方法sort(List,Comparator)不适用于参数(ArrayList,EmployeeSortById)

但在我的EmployeeSortById课程中,我已正确实施Comparator<Employee>。它还在给出问题。有人可以指导我吗?

1 个答案:

答案 0 :(得分:0)

您需要在使用

之前定义EmployeeSortById
public class EmployeeSortById implements Comparator{

public int compare(Employee o1, Employee o2) {
    Employee p1 = (Employee) o;
    Employee p2 = (Employee) o; 
    return p1.getEmployeeId() - p2.getEmployeeId();
}}

public void sortByID() {

    System.out.println("----Sort By Employee Id----");
    Collections.sort(emp,EmployeeSortById );
}