【问题标题】:java: Sorting objects in collection [duplicate]java:对集合中的对象进行排序[重复]
【发布时间】:2013-06-02 07:48:25
【问题描述】:

我写了一个这样的代码,它从一个文件夹中的文本文件(150 个文本文件)创建 150 个员工对象并将其存储在一个集合中。

这些文本文件包含员工的 id、姓名和年龄。

我的问题是我想对这 150 名员工的 ID、姓名和年龄进行排序。我应该如何编写它。我应该实现比较器还是可比较的接口?并实施它。 请指导我

代码如下:

package com.fulcrum.emp;

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

public class TestingColections {

    public static void main(String[] args) {

        File folder = new File("D:\\employee files");
        File[] listOfFiles = folder.listFiles();
        ArrayList<Employee> emp= new ArrayList<Employee>();;
        int id = 0;
        String name = null;
        int age = 0;
        for (File file : listOfFiles) {

            try {
                Scanner scanner = new Scanner(file);

                String tokens = "";
                String[] newtokens = null;

                while (scanner.hasNext()) {

                    tokens = tokens.concat(scanner.nextLine()).concat(" ");

                    tokens = tokens.replace("=", "|");
                    newtokens = tokens.split("[|\\s]");

                }

                id = Integer.parseInt(newtokens[1]);
                name = (newtokens[3] + " " + newtokens[4]);
                age = Integer.parseInt(newtokens[6]);



                emp.add(new Employee(id, name, age));




            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }


        }

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

    }

}

【问题讨论】:

  • 你想存放在哪里

标签: java


【解决方案1】:

一种方法是使用Collections.sort() 方法...

根据其元素的自然顺序将指定列表按升序排序。列表中的所有元素都必须实现 Comparable 接口。

Comparable 接口只定义了一种方法...

返回负整数、零或正整数,因为此对象小于、等于或大于指定对象。

因此,如果您的 Employee 对象要按 ID 排序,那么以下内容将帮助您完成:

public class Employee implements Comparable<Employee> {

    // Existing code


    public int compareTo( Employee e ) {
        return this.id - e.getId();
    }
} 

如果您想按员工姓名订购,那么方法可能是这样的:

@Override
public int compareTo( Employee arg0 ) {
    return this.name.compareTo( arg0.getName() );
}

要对集合进行排序,请在循环并打印值之前使用Collections.sort( emp );

【讨论】:

    猜你喜欢
    • 2010-11-15
    • 1970-01-01
    • 1970-01-01
    • 2011-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-24
    相关资源
    最近更新 更多