WEB开发网
开发学院软件开发Java 技巧:当不能抛出异常时 阅读

技巧:当不能抛出异常时

 2010-05-04 00:00:00 来源:WEB开发网   
核心提示: importjava.io.IOException;importjava.util.ArrayList;importjava.util.List;publicclassIOSorter{publicstatic<T>voidsort(List<T>list,IOCompa

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); 
  } 
 
}

上一页  1 2 3 4 5 6 7  下一页

Tags:技巧 不能 异常

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接