日期:2014-05-16 浏览次数:21026 次
package org.apache.commons.io.comparator;
import java.io.File;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/*公共的接口的方法是Comparator的campare(arg1,arg2)*/
abstract class AbstractFileComparator implements Comparator<File> {
    public File[] sort(File... files) {
        if (files != null) {
            Arrays.sort(files, this);
        }
        return files;
    }
    public List<File> sort(List<File> files) {
        if (files != null) {
            Collections.sort(files, this);
        }
        return files;
    }
    @Override
    public String toString() {
        return getClass().getSimpleName();
    }
}
/*部分都实现了Comparator的compare方法只是实现的方法不一样这里只给出DefaultFileComparator的实现方式*/
/**
     * Compare the two files using the {@link File#compareTo(File)} method.
     * 
     * @param file1 The first file to compare
     * @param file2 The second file to compare
     * @return the result of calling file1's
     * {@link File#compareTo(File)} with file2 as the parameter.
     */
    public int compare(File file1, File file2) {
        return file1.compareTo(file2);
    }
/*整体也需要实现compare方法,这里使用了部分的compare的具体的实现*/
/**
     * Compare the two files using delegate comparators.
     * 
     * @param file1 The first file to compare
     * @param file2 The second file to compare
     * @return the first non-zero result returned from
     * the delegate comparators or zero.
     */
    public int compare(File file1, File file2) {
        int result = 0;
        for (Comparator<File> delegate : delegates) {
            result = delegate.compare(file1, file2);
            if (result != 0) {
                break;
            }
        }
        return result;
    }
/*整体需要有个接口来组合部分,在这个类的构造方法中有体现*/
private static final Comparator<?>[] NO_COMPARATORS = {};
    private final Comparator<File>[] delegates;
    /**
     * Create a composite comparator for the set of delegate comparators.
     *
     * @param delegates The delegate file comparators
     */
    @SuppressWarnings("unchecked") // casts 1 & 2 must be OK because types are already correct
    public CompositeFileComparator(Comparator<File>... delegates) {
        if (delegates == null) {
            this.delegates = (Comparator<File>[]) NO_COMPARATORS;//1
        } else {
            this.delegates = (Comparator<File>[]) new Comparator<?>[delegates.length];//2
            System.arraycopy(delegates, 0, this.delegates, 0, delegates.length);
        }
    }
    /**
     * Create a composite comparator for the set of delegate comparators.
     *
     * @param delegates The delegate file comparators
     */
    @SuppressWarnings("unchecked") // casts 1 & 2 must be OK because types are already correct
    public CompositeFileComparator(Iterable<Comparator<File>> delegates) {
        if (delegates == null) {
            this.delegates = (Comparator<File>[]) NO_COMPARATORS; //1