技巧:当不能抛出异常时
2010-05-04 00:00:00 来源:WEB开发网import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class IOSorter {
public static <T> void sort(List<T> list, IOComparator<? super T> comparator)
throws IOException {
List<T> temp = new ArrayList<T>(list.size());
temp.addAll(list);
bubblesort(temp, comparator);
// copy back to original list now that no exceptions have been thrown
list.clear();
list.addAll(temp);
}
// of course you can replace this with a better algorithm such as quicksort
private static <T> void bubblesort(List<T> list, IOComparator<? super T> comparator)
throws IOException {
for (int i = 1; i < list.size(); i++) {
for (int j = 0; j < list.size() - i; j++) {
if (comparator.compare(list.get(j), list.get(j + 1)) > 0) {
swap(list, j);
}
}
}
}
private static <T> void swap(List<T> list, int j) {
T temp = list.get(j);
list.set(j, list.get(j+1));
list.set(j + 1, temp);
}
}
赞助商链接