Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- import java.io.*;
- public class CompareTest {
- public static void main(String[] args) throws IOException {
- List<Integer> ints = new ArrayList<Integer>();
- List<File> files = new ArrayList<File>();
- for (int i = 0; i < 245; ++i) {
- ints.add(i);
- }
- Collections.shuffle(ints);
- for (Integer i : ints) {
- File file = new File("file-" + i);
- file.createNewFile();
- files.add(file);
- }
- compare(ints, new IntsComparator());
- compare(files, new FilesComparator());
- }
- private static <T> void compare(List<T> list, CountingComparator<T> comparator) {
- int startCount = comparator.getCount();
- long start = System.nanoTime();
- Collections.sort(list, comparator);
- long end = System.nanoTime();
- long nanos = end - start;
- double seconds = nanos / 1000000000.0D;
- int endCount = comparator.getCount();
- System.out.printf("%s took %f seconds with %d comparisons%n", comparator.getClass().getSimpleName(), seconds, endCount - startCount);
- }
- private interface CountingComparator<T> extends Comparator<T> {
- int getCount();
- }
- private static class IntsComparator implements CountingComparator<Integer>
- {
- @Override
- public int compare(Integer o1, Integer o2) {
- ++count;
- return o1 - o2;
- }
- @Override
- public int getCount() {
- return count;
- }
- int count = 0;
- }
- private static class FilesComparator implements CountingComparator<File>
- {
- @Override
- public int compare(File o1, File o2) {
- ++count;
- return (int)(o1.lastModified() - o2.lastModified());
- }
- @Override
- public int getCount() {
- return count;
- }
- int count = 0;
- };
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement