/*部分都实现了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
} else {
List<Comparator<File>> list = new ArrayList<Comparator<File>>();
for (Comparator<File> comparator : delegates) {
list.add(comparator);
}
this.delegates = (Comparator<File>[]) list.toArray(new Comparator<?>[list.size()]); //2
}
}