1. import java.util.*;
  2. import java.io.*;
  3.  
  4. public class CompareTest {
  5.     public static void main(String[] args) throws IOException {
  6.         List<Integer> ints = new ArrayList<Integer>();
  7.         List<File> files = new ArrayList<File>();
  8.         for (int i = 0; i < 245; ++i) {
  9.             ints.add(i);
  10.         }
  11.         Collections.shuffle(ints);
  12.  
  13.         for (Integer i : ints) {
  14.             File file = new File("file-" + i);
  15.             file.createNewFile();
  16.             files.add(file);
  17.         }
  18.  
  19.         compare(ints, new IntsComparator());
  20.         compare(files, new FilesComparator());
  21.     }
  22.  
  23.     private static <T> void compare(List<T> list, CountingComparator<T> comparator) {
  24.         int startCount = comparator.getCount();
  25.         long start = System.nanoTime();
  26.         Collections.sort(list, comparator);
  27.         long end = System.nanoTime();
  28.         long nanos = end - start;
  29.         double seconds = nanos / 1000000000.0D;
  30.         int endCount = comparator.getCount();
  31.         System.out.printf("%s took %f seconds with %d comparisons%n", comparator.getClass().getSimpleName(), seconds, endCount - startCount);
  32.     }
  33.  
  34.     private interface CountingComparator<T> extends Comparator<T> {
  35.         int getCount();
  36.     }
  37.  
  38.     private static class IntsComparator implements CountingComparator<Integer>
  39.     {
  40.         @Override
  41.         public int compare(Integer o1, Integer o2) {
  42.             ++count;
  43.             return o1 - o2;
  44.         }
  45.  
  46.         @Override
  47.         public int getCount() {
  48.             return count;
  49.         }
  50.  
  51.         int count = 0;
  52.     }
  53.  
  54.     private static class FilesComparator implements CountingComparator<File>
  55.     {
  56.         @Override
  57.         public int compare(File o1, File o2) {
  58.             ++count;
  59.             return (int)(o1.lastModified() - o2.lastModified());
  60.         }
  61.  
  62.         @Override
  63.         public int getCount() {
  64.             return count;
  65.         }
  66.  
  67.         int count = 0;
  68.     };
  69. }