5

我有一些代码可以按修改日期对路径进行排序。我还想编写一些代码来以相反的顺序对路径进行排序,并且以后可能想要添加一些其他排序方法。有没有办法从单个类文件中进行所有排序?或者我是否必须创建另一个类 PathSortByDateReverse、PathSortByCreated、PathSortByFoo 等。另外,我将如何使用不同的排序方法?

import java.nio.file.Path;
import java.util.Comparator;

public class PathSortByDate implements Comparator<Path> {

@Override
public int compare(Path first, Path second) {
    long seconddate = second.toFile().lastModified(); // get just the filename
    long firstdate = first.toFile().lastModified();

    if (firstdate == seconddate) {
        return 0;
    } else if (firstdate > seconddate) {
        return 1;
    } else {
        return -1;
    }
}
}

然后我从另一个类中调用它:

public static ArrayList<Path> sortArrayListByDate(ArrayList<Path> pathlist) {
    Collections.sort(pathlist,new PathSortByDate());
    return pathlist;
}    
4

3 回答 3

3

为什么不选择匿名内部类?

public static final Comparator<Person> ID_DESC
     = new Comparator<Person>() {
      public int compare(Person p1, Person p2) {
         return -1 * p1.getId().comparedTo(p2.getId());
         // reversed order
      }
    };
于 2012-04-25T05:50:58.183 回答
2

我通常会这样做。请注意,构造函数是“私有的”,并且有一个“公共工厂方法”来获取实例。在任何给定点都会存在两个 PathComparator 实例。如果您要优化代码并使用最佳实践,这将是一件大事。

import java.nio.file.Path;
import java.util.Comparator;

final public class PathComparator implements Comparator<Path> {

// comparator for in order
final private static PathComparator ascendingOrderComparatorDate = new PathComparator(true);
// comparator for reverse order
final private static PathComparator descendingOrderComparatorDate = new PathComparator(false);

final private int isAscendingOrderInt;

final public PathComparator getPathComparator(boolean isAscendingOrder) {
    return isAscendingOrder ? ascendingOrderComparatorDate : descendingOrderComparatorDate;
}

private PathComparator(boolean isAscendingOrder) {
    this.isAscendingOrderInt = isAscendingOrder ? 1 : -1;
}

@Override
public int compare(Path first, Path second) {
    // for optimization (not required but highly recommended)
    if(first == second) return 0;

    long seconddate = second.toFile().lastModified(); // get just the filename
    long firstdate = first.toFile().lastModified();

    if (firstdate == seconddate) {
        return 0;
    } else if (firstdate > seconddate) {
        return isAscendingOrderInt * 1;
    } else {
        return isAscendingOrderInt * -1;
    }
}}
于 2012-04-25T06:18:44.987 回答
1

您不需要制作反向比较器,只需制作它并使用

Collections.reverseOrder()
于 2012-04-25T05:44:54.433 回答