我有一些代码可以按修改日期对路径进行排序。我还想编写一些代码来以相反的顺序对路径进行排序,以后可能会想要添加一些其他的排序方法。有没有办法从单个类文件中进行所有排序?或者我是否必须创建另一个类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;
}
答案 0 :(得分: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
}
};
答案 1 :(得分: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;
}
}}
答案 2 :(得分:1)
你不需要制作反向比较器,只需制作它并用
反转它Collections.reverseOrder()