2012-04-25 58 views
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; 
}  

回答

1

你不需要做反向比較,只是使它與

Collections.reverseOrder() 
+0

謝謝,我想到了,但我可能想在以後添加其他排序方法,基本上想更好地瞭解它是如何工作的。 – localhost 2012-04-25 05:47:05

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 
     } 
    }; 
+0

你可以得到更多的信息[這裏](http://stackoverflow.com/questions/10309929/implementing-comparator-multiple-times-in-a-single-class-file/10310033#10310033) – 2012-04-25 05:51:44

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; 
    } 
}}