Java practical tips: When a checked exception cannot be thrown (2)

Source: Internet
Author: User
Tags addall

Split the problem into two parts

The first method is to split the problem into two parts. The comparison itself does not cause exceptions. Only strings are compared. Converting a file to a string through the standard path causes an exception. If you separate operations that may throw exceptions from those that do not throw exceptions, the problem is easier to handle. That is to say, first convert all file objects to strings, and then use the string comparator (or even through java. lang. sort the strings. Finally, sort the original file list by the sorted String list. This method is not straightforward, but the advantage is that IOException is thrown before the list is changed. If an exception occurs, it only appears in a pre-designed place without causing any damage. The calling code can specify how to handle the exception. Listing 4 demonstrates this:

Listing 4. read first, and then sort importjava. io. file; importjava. io. IOException; importjava. util. arrayList; importjava. util. collections; importjava. util. hashMap; publicclassFileComparator {parameters <String> getCanonicalPaths (ArrayList <File> files) throwsIOException {ArrayList <String> paths = newArrayList <String> (); for (Filefile: files) paths. add (file. getCanonicalPath (); returnpaths;} publicstaticvoidmain (String [] Args) throwsIOException {ArrayList <File> files = newArrayList <File> (); for (Stringarg: args) {files. add (newFile (arg);} ArrayList <String> paths = getCanonicalPaths (files); // tomaintaintheoriginalmapping HashMap <String, File> map = newHashMap <String, File> (); inti = 0; for (Stringpath: paths) {map. put (path, files. get (I); I ++;} Collections. sort (paths); files. clear (); for (Stringpath: paths) {files. add (map. get (path) ); }}} Listing 4 does not eliminate the possibility of an I/O error. This cannot be done because the code here cannot provide such a function. However, the problem can be handled in a more appropriate way.

Avoid Problems

The method mentioned above is a little complicated, so I suggest another method: Do not use the built-in compare () function or Collections. sort (). It may be convenient to use such a function, but it is not suitable for the current situation. Comparable and Comparator are designed for definite and predictable comparison operations. Once I/O no longer meets this situation, it is very likely that common algorithms and interfaces become unsuitable. Even if it is barely usable, its efficiency is extremely low.

For example, it is assumed that files are compared by content rather than by standard paths. For the two files to be compared, each comparison operation requires reading the content of the file-or even the complete content. In this way, the efficient algorithm will try to reduce the number of reads, and may want to cache the results of each read-or, if the file is large, the hashcode of each file may be cached-instead of re-reading each file during each comparison. Similarly, you will first fill in a comparison key list and then sort it, instead of inline sorting. You can imagine defining a separate and parallel IOComparator interface that throws necessary exceptions, as shown in listing 5:

Listing 5. independent IOComparator interface importjava. io. IOException; publicinterfaceIOComparator <T> {intcompare (To1, To2) throwsIOException;} then define a separate, similar utility tree based on this class, it performs necessary operations on the temporary copy of the set, so that an exception can be thrown without putting the data structure in a potentially damaged and intermediate state. For example, listing 6 provides a basic Bubble Sorting:

Listing 6. sort files using the bubble algorithm importjava. io. IOException; importjava. util. arrayList; importjava. util. list; publicclassIOSorter {publicstatic <T> voidsort (List <T> list, IOComparator <? SuperT> comparator) throwsIOException {List <T> temp = newArrayList <T> (list. size (); temp. addAll (list); bubblesort (temp, comparator); // copybacktooriginallistnowthatnoexceptionshavebeenthrown list. clear (); list. addAll (temp);} // ofcourseyoucanreplacethiswithabetteralgorithmsuchasquicksort privatestatic <T> voidbubblesort (List <T> list, IOComparator <? SuperT> comparator) throwsIOException {for (inti = 1; I <list. size (); I ++) {for (intj = 0; j <list. size ()-I; j ++) {if (comparator. compare (list. get (j), list. get (j + 1)> 0) {swap (list, j) ;}}} privatestatic <T> voidswap (List <T> list, intj) {Ttemp = list. get (j); list. set (j, list. get (j + 1); list. set (j + 1, temp) ;}} is not the only method. For clarity, listing 6 intentionally imitates existing Collections. sort () method; however, a more effective method is to return a new list, rather than directly modifying the old list, to prevent the damage caused by exceptions thrown when the list is modified.


 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.